Reputation: 360
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?
Upvotes: 0
Views: 186
Reputation: 360
I still do not understand the output, but I found a quite consistent solution for reading a binary file using a buffer. http://www.cplusplus.com/doc/tutorial/files/
Upvotes: 0
Reputation: 66190
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 charssizeof(charsRead) - sizeof(char*)
uninitialized chars (so, casual values).Upvotes: 2