io:fail

C++ Reference

fail

Syntax:

    #include <fstream>
    bool fail();

The fail() function returns true if an error has occurred with the current stream, false otherwise. This can be used for checking whether the previous operation has failed.

Examples of failures that cause fail to be set:

  • file not found (when opening for reading).
  • file cannot be created (when opening for writing).
  • end of file is reached before the requested data could be read.
  • invalid formatting of data (e.g. letters when expecting numbers).

Once set, the fail state will make all other operations on the stream fail instantly, until the error state is cleared with the clear function.

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

Stream states:

  • 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.