Testing Whether a File Was Opened Successfully
After creating an
ofstream object and attempting to open it, the program tests whether the open operation was successful. The
if statement in lines 15–19 uses the overloaded
ios member function
operator! to determine whether the
open operation succeeded. The condition returns a
true value if either the
failbit or the
badbit (see Chapter 13) is set for the stream on the
open operation. Some possible errors are attempting to open a nonexistent file for reading, attempting to open a file for reading or writing from a directory that you don’t have permission to access, and opening a file for writing when no disk space is available.
If the condition indicates an unsuccessful attempt to open the file, ...