Home c++ Proper use of end-of-file checking

Proper use of end-of-file checking

Author

Date

Category

When using code

while (! feof (file))
{
  // Read from file
}

in C or

while (! file.eof ())
{
  // Read from file
}

in C++ you get into trouble – an extra read line, for example. Why? What is the correct way to check that the end of the file has been reached?


Answer 1, authority 100%

The sign of reaching the end of the file is set only after an unsuccessful attempt to read past its end . Therefore, if there is no check in the body of the loop whether the read from the file was successful, the last read will turn out to be exactly that unsuccessful read, which will set the sign of the reached end of the file (and for you it will look like, for example, again the last line read, if it was in the read buffer).

It is better to do the reading itself with a check in the head of the while loop – for example, in a C program it might look like

while (fread (& amp; data, sizeof (data), 1, file) == 1)
{
  // Process the read data
}
/ * Or, say
while (fgets (buf, bufsize, file)) {....}
* /
if (feof (file)) // End Of File Reached
  puts ("Read error: end of file reached");
else if (ferror (file)) {
  puts ("Error reading file");

or in C++ – like

for (int n; file & gt; & gt; n;)
{
  // Process the read value n
}
if (file.bad ())
  std :: cout & lt; & lt; "I / O error while reading \ n";
else if (file.eof ())
  std :: cout & lt; & lt; "End of file reached \ n";
else if (file.fail ())
std :: cout & lt; & lt; "Invalid data format \ n";

Answer 2, authority 24%

In addition to the eof flag, after reading the entire file, the fail flag can also be set, and if we want to set the cursor to the beginning of fin.seekg (0, fin. beg) , then we won’t read anything, because the fail flag was not cleared. Reset can be done with fin.clear () . The current state can be displayed by fin.rdstate () :

ifstream fin;
fin.open ("E: //1.txt", ios_base :: in);
string str;
while (getline (fin, str)) {
  cout & lt; & lt; str & lt; & lt; "" & lt; & lt; fin.rdstate () & lt; & lt; endl;
}
if (fin.bad ())
  std :: cout & lt; & lt; "bad" & lt; & lt; endl;
if (fin.eof ())
  std :: cout & lt; & lt; "eof" & lt; & lt; endl;
if (fin.fail ())
  std :: cout & lt; & lt; "bad | fail" & lt; & lt; endl;
fin.clear ();
fin.seekg (0, fin.beg);
if (fin.bad ())
  std :: cout & lt; & lt; "bad" & lt; & lt; endl;
if (fin.eof ())
  std :: cout & lt; & lt; "eof" & lt; & lt; endl;
if (fin.fail ())
  std :: cout & lt; & lt; "bad | fail" & lt; & lt; endl;
while (getline (fin, str)) {
  cout & lt; & lt; str & lt; & lt; "" & lt; & lt; fin.rdstate () & lt; & lt; endl;
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions