1

When I try to determine end of file with function feof(FILE *), I find it does not work as I expected: an extra read is required even if the stream does end. E.g., feof(FILE*) will not return true if invoked on a file with 10 bytes data just after reading 10 bytes out. I need an extra read operation which of course returns 0. Then feof(FILE *) will say "OK, now you reach the end."

Why is one more read required and how can I determine end of file or how can I know how many bytes are left in a file stream if I don't want the feof-style?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Summer_More_More_Tea
  • 12,740
  • 12
  • 51
  • 83
  • http://c-faq.com/stdio/feof.html – Mat May 17 '11 at 11:07
  • 1
    possible duplicate of [In C, is "while( !feof( ... ) )" always wrong?](http://stackoverflow.com/questions/5431941/in-c-is-while-feof-always-wrong) – Bo Persson May 17 '11 at 11:58
  • 2
    Think of a stream as water behind a tap. When you want something *(a char: `getchar()`, a line: `fgets()`, a bunch of data: `fread()`, ...)* you open the tap, get what you want, and close the tap. If it worked you can't know if there is more water; or if the tap is going to break next. If it failed, you can determine **why** it failed: because there was not enough water (`feof` is true); or because the tap broke (`ferror` is true). – pmg May 17 '11 at 12:03

1 Answers1

11

Do not use feof() or any variants—it is as simple as that. You want it to somehow predict the next read will fail, but that's not what it does - it tells you what the result of the previous read was. The correct way to read a file is (in pseudocode):

while(read(file, buffer)) {
   // Do something with buffer
}

In other words, you need to test the result of the read operation. This is true for both C streams and C++ iostreams.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131