0

How to check whether end of file is reached or not without having to read the next string?

Actually the case is that, in my code, I want to check two times whether the next character leads to end of file or not. First time I will check it by reading the next string but second time I can't check this way becoz the required string has already been read. So how to check the the second time without having to read the string again or moving the file pointer behind...

(file.peek() does not solve the problem. That has been explained in comment.)

  • 2
    Possible duplicate of [How to know if the next character is EOF in C++](https://stackoverflow.com/questions/6283632/how-to-know-if-the-next-character-is-eof-in-c) – user8153 Sep 08 '17 at 23:58
  • I had seen it... That file.peek() is not giving proper results... It is also printing the last string twice like file.eof() does. – Priya Singh Sep 09 '17 at 04:13

1 Answers1

0

I want to check two times whether the next character leads to end of file or not.

  1. Before you start reading the file, find the length of the contents. See calculate size of file for how to do that.

  2. At any time, you can query the position of the file using tellg(). If the position is exactly one less than the length of the contents, you know that reading the next character will lead to the end of file.

R Sahu
  • 204,454
  • 14
  • 159
  • 270