How to know if the next character is EOF in C++
This should work:
if (file.peek(), file.eof())
But why not just check for errors after making an attempt to read useful data?
istream::peek()
returns the constant EOF
(which is not guaranteed to be equal to -1) when it detects end-of-file or error. To check robustly for end-of-file, do this:
int c = file.peek();
if (c == EOF) {
if (file.eof())
// end of file
else
// error
} else {
// do something with 'c'
}
You should know that the underlying OS primitive, read(2)
, only signals EOF when you try to read past the end of the file. Therefore, file.eof()
will not be true when you have merely read up to the last character in the file. In other words, file.eof()
being false does not mean the next read operation will succeed.