Turbo C++ : while(fin) vs while(!fin.eof())

Alpha Mineron picture Alpha Mineron · Jun 22, 2017 · Viewed 10.1k times · Source

I was told that I should be using while(fin) instead of while(!fin.eof()) when reading a file.

What exactly is the difference?

Edit: I do know that while(fin) actually checks the stream object and that when it becomes NULL, the loop breaks and it covers eof and fail flags. But my course teacher says that fin.eof() is better so I need to understand the fundamental operation that's going on here.

Which one is the right practice?

Note: This is not a duplicate, I need assistance in Turbo C++ and with binary files. I'm basically trying to read a file using a class object.

Answer

The boy who lived picture The boy who lived · Jul 8, 2017

First of all I am assuming fin is your fstream object. In which case your teacher would not have told you to use while(fin.eof()) for reading from file. She would have told to use while(!fin.eof()).

Let me explain. eof() is a member of the fstream class which returns a true or false value depending on whether the End Of File (eof) of the file you are reading has been reached. Thus while eof() function returns 0 it means the end of file has not been reached and loop continues to execute, but when eof() returns 1 the end of the file has been reached and the loop exits.

while(fin) loop is entered because fin actually returns the value of an error flag variable inside the class object fin whose value is set to 0 when any function like read or write or open fails. Thus the loop works as long as the read function inside the loop works.

Personally I would not suggest either of them. I would suggest

//assume a class abc.

abc ob;


While(fin.read((char*)&ob, sizeof(ob)))
{}

Or

While(fin.getline(parameters))
{}

This loop reads the file record inside the loop condition and if nothing was read due to the end of file being reached, the loop is exited.

The problem with while(!fin.eof()) is that it returns 1 if the end of file has been reached. End of file is actually a character that is put at the end of the file. So when the read function inside the loop reads this character and sets a variable eof to 1. All the function actually does is return this value.

Thus works fine when you are reading lines in words but when you are reading successive records of a class from a file, this method will fail. Consider

clas abc
{}a;

Fstream fin("file");


While(!fin.eof())


{
  fin.read((char*)&a,sizeof(a));


  a.display();  // display is a member function which displays the info }

Thus displays the last record twice. This is because the end of file character is the character after the last byte of the last record. When the last is read the file pointer is at the eof byte but hasn't read it yet. So it will enter the loop again but this time the eof char is read but the read function fails. The values already in the variable a, that is the previous records will be displayed again.