Problem with EOF when determine stream end

2019-01-20 06:24发布

问题:

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 tell 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 return 0, then feof(FILE *) will say "OK, now you reach the end."

My question is why does one more read required and how to determine end of file or how to know how many bytes left in a file stream if I don't want the feof-style?

Thanks and Best Regards.

回答1:

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.



标签: c++ c io eof