Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if the next character is EOF in C++

Tags:

c++

eof

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.

like image 649
Tae Avatar asked Jun 08 '11 18:06

Tae


People also ask

Is EOF and \n same?

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.

Where is EOF defined in C?

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.

How does EOF compare to string?

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.


1 Answers

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.

like image 198
zwol Avatar answered Oct 20 '22 21:10

zwol