io:eof

C++ Reference

eof

Syntax:

    #include <fstream>
    bool eof();

The function eof() returns true if the end of the associated input file has been reached, false otherwise.

A stream goes into EOF state whenever the end of stream is seen, i.e. a character past the end has been read. As operator» and getline normally keep reading characters until the end of token (until whitespace, invalid characters, line terminator or EOF) it is possible that the stream EOF flag gets set even though the token was read correctly. Conversely, the stream does not go into EOF state if there happens to be any whitespace after the last token, but trying to read another token will still fail.

Therefore, the EOF flag cannot be used as a test in a loop intended to read all stream contents until EOF.

Instead, one should check for the fail condition after an attempt to read. This is done most conveniently by testing the stream itself, as follows:

   std::ifstream file("test.txt");
   std::string line;
   while (std::getline(file, line)) {
     // A line was read successfully, so you can process it
   }

Line 7 of the example below illustrates the main use for checking the EOF state: after a failed read. In such a situation, it can be used to determine whether or not the fail was caused by reaching the end of stream.

1:    std::ifstream file("test.txt");
2:    std::string word;
3:    double value;
4:    while (file >> word >> value) {
5:      // A word and a double value were both read successfully
6:    }
7:    if (!file.eof()) throw std::runtime_error("Invalid data from file");

The table below lists a number of different states that a stream may be in:

TestDescription
if (s)The previous operation was successful (a shorthand for !s.fail()).
if (s.fail())The previous operation failed.
if (s.eof())Reading past the end has been attempted.
if (s.bad())Stream state is undefined; the stream can no longer be used.
if (s.good())None of bad/eof/fail are set.

Related Topics: bad, clear, exceptions, fail, good, rdstate