I'm need to know if the next char in ifstream
is the end of file. I'm trying to do this with .peek()
:
if (file.peek() == -1)
and
if (file.peek() == file.eof())
But neither works. There's a way to do this?
Edit: What I'm trying to do is to add a letter to the end of each word in a file. In order to do so I ask if the next char is a punctuation mark, but in this way the last word is left without an extra letter. I'm working just with char
, not string
.
A return value of EOF from fgetc() and friends can occur at any time - even in the middle of a line due to an error. Otherwise, no: A end-of-file does not occur at the end of a line with a '\n' . Typically the last line in a file that contains at least 1 character (and no `'\n') will also be a line.
With the GNU C Library, EOF is -1 . In other libraries, its value may be some other negative number. This symbol is declared in stdio. h . Macro: int WEOF.
There is no way of comparing a string with EOF; it is not a char value, but a condition on the stream (here, stdin ). However the getchar() and alike will return the read char value as unsigned char cast to an int , or EOF if end-of-file was reached, or an error occurred.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With