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, line 17 outputs the error message "File could not be opened"
, and line 18 invokes function exit
to terminate the program. The argument to exit
is returned to the environment from which the program was invoked. Passing EXIT_SUCCESS
(also defined in <cstdlib>
) to exit
indicates that the program terminated normally; passing any other value (in this case EXIT_FAILURE
) indicates that the program terminated due to an error.