'Problem with EOF when determining stream end
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?
Solution 1:[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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Peter Mortensen |