Search code examples
c++c++11binaryfilesreadfile

Inconsistent output when reading binary file


Adapting some of the code I have seen in SO, I came out with the following solution:

fstream file("sample.bin", ios::binary | ios::in | ios::ate);

unsigned char charsRead[(int)file.tellg()];

file.read((char *) &charsRead, sizeof(char*));
for(int i=0; i<sizeof(charsRead); i++) 
    cout << (int) charsRead[i] << endl;
file.close();

It does compile, but every time is executed, it returns a different output. Does anyone know why this is happening?


Solution

  • I suppose that the first 4 (or 8) bytes are ever equals and that the different output start from 5th or 9th byte.

    As pointed by πάντα ῥεῖ, You read sizeof(char*) bytes (usually 4 or 8 bytes) and you print sizeof(charsRead) bytes.

    If sizeof(char*) < sizeof(charsRead) (that is: if the dim of the file is bigger that 4 or 8), you write

    • sizeof(char*) initialized chars
    • sizeof(charsRead) - sizeof(char*) uninitialized chars (so, casual values).