0

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?

3
  • Are you sure sizeof(char*) does what you think it does? Commented Oct 11, 2016 at 11:08
  • 1
    unsigned char charsRead[(int)file.tellg()]; is a non standard VLA. If you need to read into a char buffer consider a std::vector<unsigned char>. Commented Oct 11, 2016 at 11:34
  • Mmmm not really. But even when that number is a constant, it still returns different outputs when executing different times, so that does not explain the changes. Commented Oct 11, 2016 at 11:38

2 Answers 2

2

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).
Sign up to request clarification or add additional context in comments.

2 Comments

I still do not understand something. Even if it is wrong, why is the output inconsistent given the same input file?
@AlvaroGomez - I've tryed to explain it in my answer; short answer: you're not reading the input file, you're printing random values
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.