user5403707
user5403707

Reputation:

End of file of fstream object

I came across this code which deals with a simple reading of a file and displaying its contents.

#include <iostream>
#include <fstream>

int main()
{   
    ...
    fstream file;
    file.open("TEXT.txt", ios::in);
    file.seekg(0);
    while(file) //does file returns 0 when eof is reached?
    {
        file.get(ch);
        cout << ch;
    }
    return 0;
}

My question is how does while (file) realizes that the end of the file has been reached.

Upvotes: 2

Views: 753

Answers (2)

Zaid Khan
Zaid Khan

Reputation: 826

As others have pointed out you should really use something like

char ch;
while (file.get(ch)) {
    ...
}

Upvotes: 0

Alex Fitzpatrick
Alex Fitzpatrick

Reputation: 644

The stream implements a boolean cast operator that will return true if the stream is still good or false if there's an error or eof.

Upvotes: 5

Related Questions