Angelo
Angelo

Reputation: 61

Why is the failbit being set. File seems to have printed fine

I have a piece of code that does the work it is intended to do but I have doubts about failbit. Th catch block always runs although the file is displayed on the screen. When eof is reached why is failbit set? Maybe I am not understanding the right meaning of failbit..Has something failed?

    int main()
    {
        ifstream infile;
        char c;
        infile.exceptions ( ifstream::failbit );

        try
        {
            infile.open("../Dose.c", ios::in);
            while (!infile.eof())
            {   
                c=infile.get();
                cout << c;
            }
            infile.close();

        }
        catch(ifstream::failure e)
        {
            cout << infile.eof() << " " << infile.fail() << " " << infile.bad() << " " << infile.good() ; 
            cerr << " Exception opening/reading/closing file\n";
        }
    return 0;
    }

The OUTPUT: 1 1 0 0 Exception opening/reading/closing file. So clearly fail() and eof is set.

Upvotes: 0

Views: 373

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118330

27.5.5.4, paragraph 7:

bool eof() const; Returns: true if eofbit is set in rdstate().

In other words, all that eof() does is check if eofbit is already set. It doesn't "actively" check if the end of file has been reached.

Skipping a bunch of dry, formal, specifications, what happens is that the end of file condition gets detected inside get(). eofbit gets set first, then failbit (the get() operation failed). Because you enabled exceptions, the act of setting the failbit throws an exception. If exceptions were not enabled, get() would return traits::eof(), typically -1, instead of the character read from the file.

Takeaway:

  1. When using exceptions, eof()'s only value comes after the exception is already thrown, to determine whether the exception was due to an end of file condition. In your example, eof() will never return true.
  2. When not using exceptions, eof() is not really needed, just check if get() returned -1.

Upvotes: 1

Related Questions