Search code examples
c++file-iobinaryistream

istream::read not filling char array correctly


I'm opening an istream for binary read:

ifstream file;
file.open (this -> fileName.c_str(), ios::binary);

I then try to read, while the file is good, into a char array pointer:

char data[numberOfBytes];
char * p = data;
file.read(p, numberOfBytes);
cout << "size: "   << sizeof(p)     << end
cout << "gcount: " << file.gcount() << endl;
cout << "strlen: " << strlen(p)     << endl;

The output is different for each of the above. Sizeof() produces 4 which is correct size of char pointer. gcount() produces whatever value numberOfBytes has. However, strlen() returns some other smaller number. So, although read() has moved the istream pointer numberOfBytes, I do not have these bytes in the char array. I want all those bytes in the char array. How do I achieve this? What is going on?


Solution

  • If you're reading in binary data then it's possible that you're reading a byte with a value of zero, or a null character in string terminology.

    The way strlen() calculates the size of a string is by starting at the beginning of the string, and counting until it reaches a null character.

    Thus strlen() will only report the number of bytes up to the null character, not the actual number of bytes read.