0
char buf[25];
ifstream fin("test.txt", ifstream::binary);
while (!fin.eof()) {
    bzero(buf, sizeof(buf));
    fin.read(buf, sizeof(buf));
}

The file test.txt contains 75 characters, no newlines or any other special character. Given the code, the while loop should only iterate 3 times, but it ends up iterating 4 times. During the last iteration, nothing is being stored in the buf variable. Why is this happening?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
ExtremistEnigma
  • 239
  • 3
  • 12
  • There is no `ifstream` type in C. Please don't mistag (or dual tag) a question with both C and C++ unless you're sure the question is appropriate to both languages — which will very seldom be the case. – Jonathan Leffler Mar 09 '16 at 04:28

1 Answers1

3

fstream.eof only becomes true when you have passed the end-of-file. The fourth iteration occurs because you have read exactly the contents of the file and have not yet reached the eof.

kfsone
  • 23,617
  • 2
  • 42
  • 74
  • And you can use read in the while condition, i.e. keep looping while you keep reading: `while(fin.read(...))` – John Mar 09 '16 at 04:33