C++ – fread terminating mid-read at null values. Also reading in garbage past expected data

binaryfilescfile-iofread

I am reading in pieces of a binary file using a FILE object in C++. Here is the fseek and corresponding fread call:

fseek(fp, startLocation, SEEK_SET);
fread(data, m_sizeOfData, 1, fp);

m_sizeOfData ends up being an integer greater than 400 thousand. This appears that it should read all 400 thousand+ bytes from the binary file into data (which is a char[m_sizeOfData], by the way), however it stops after about 6 or 7 characters at a unicode character that simply looks like a box. I'm thinking it might represent a null termination? I'm not positive on this. This isn't the case with every piece of the file that I am reading in. Most seem to work (generally) correctly.

Why might this be and is there a way to correctly read all of the data?

Edit:

fp is defined as such:

FILE* fp;
_wfopen_s(&fp, L"C://somedata.dat", L"rb");

This box character, in hex, is 0x06 followed by 0x00.
The data is defined by: char *data = new char[m_sizeOfData];

edit 2:

I've also noticed that another file is having some garbage loaded onto the end of it. The garbage looks like:

ýýýý««««««««îþ

Is this because it is trying to complete a certain round number of bytes?

Best Answer

You are using the count/size parameters of fread the wrong way around. Since you are reading bytes, the second parameter should be 1 and the third parameter the count:

fread(data, 1, m_sizeOfData, fp);

You can then use the return value of fread to determine how many bytes were read. If you are getting the expected count returned, then you can be comfortable that you are reading all the data you wanted. In this case, you are probably outputting the data incorrectly - if you are treating it as a NUL-terminated string, then the 0x00 you are seeing will be the end of what is printed. The 0x06 is probably the box glyph.

Related Topic