0

I am trying to read data from file (binary). I use C++ ifstream to access the data.

The file has size around 900KB, which I can tell with:

    stream.seekg(0, stream.end);
    cout << stream.tellg() << endl;
    stream.seekg(0, stream.beg);
    cout << stream.tellg() << endl;

When I tried to read from the file, the pointer moves actually more than what I want to read. When I wrote the following code to track it (I know that the 1 byte in the buffer gets overridden):

    int counter = 0;
    while (stream.good()) {
        stream.read(buffer, 1);
        cout << stream.tellg() << " " << counter++  << " " << stream.gcount() << endl;
    }
    cout << counter << endl;

What surprised me was the fact that the tellg didn't increase as much as counter. Some of the output looked like this:

...
242770 25488 1
245760 25489 1
249345 25490 1
249346 25491 1
249347 25492 1
...

As you can see the position of the file pointer sometimes jumped by 1, sometimes by numbers like 2990 or 3585. Eventually the stream goes to eofbit/failbit, despite the fact that I have read less than the file size is. What is an explanation of such behaviour? NOTE: I am using windows/visual studio

Šimon Hrabec
  • 626
  • 1
  • 7
  • 10
  • 1
    You didn't post whether you actually opened the file as a binary file. My crystal ball is telling me you opened the file in text mode. – PaulMcKenzie Oct 21 '16 at 22:23
  • Got a bit of a bug here: `while (stream.good())`. How do you know it's good? You test before you read. Evil twin of http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – user4581301 Oct 21 '16 at 22:50

0 Answers0