Search code examples
c++file-iobinaryfilesifstream

Why ifstream reader read only first 10 bytes of an image file?


Here is the code I am trying with:

ifstream fileReader("server_data\\test2.jpg", ios::in | ios::binary);
char buffer[RESP_LENGTH];
memset(buffer, '\0', RESP_LENGTH);
if (fileReader.is_open())
{
    fileReader.seekg(0);
    fileReader.read(buffer, RESP_LENGTH);
    cout << buffer<<endl<<"Length: "<<strlen(buffer);
}
fileReader.close();

Its simply reading only first few bytes. Its also differing from file to file.

I am suspecting, probably its getting a character which evaluates to NULL and thus my length and string is getting small portion only?

Any Idea what is really happening and how to fix it?


Solution

  • The problem is not in the way you are reading in but in the way you are printing out.

    If there's a \0 character this means end of string. So string operations (like strlen or printing to cout) will stop on that character (considering the string contained in your char* stops here), but it does not mean your char* array does not contain more characters....

    Instead, you should do that:

    cout << "Got " << fileReader.gcount() << "characters:";
    for ( size_t i = 0; i != fileReader.gcount(); ++i )
        cout << buffer[i];
    

    Then, you'll print all bytes you read, ignoring EOS and other special characters.

    Note that special characters will not be printed correctly (See this post). But I guess your goal is not to print that binary content.