Figure 14.3 writes data to a file, so we open the file for output by creating an ofstream
object. Two arguments are passed to the object’s constructor—the filename and the file-open mode (line 12). For an ofstream
object, the file-open mode can be either ios::out (the default) to output data to a file or ios::app to append data to the end of a file (without modifying any data already in the file). Since ios::out
is the default, the second constructor argument in line 12 is not required. Existing files opened with mode ios::out
are truncated—all data in the file is discarded. If the specified file does not yet exist, then the ofstream
object creates the file, using that filename. Prior to C++11, the filename was specified as a pointer-based string—as of C++11, it can also be specified as a string
object.
Error-Prevention Tip 14.1
Use caution when opening an existing file for output (ios::out), especially when you want to preserve the file’s contents, which will be discarded without warning.
Line 12 creates an ofstream
object named outClientFile
associated with the file clients.txt
that’s opened for output. The arguments "clients.txt"
and ios::out
are passed to the ofstream
constructor, which opens the file—this establishes a “line of communication” with the file. By default, ofstream
objects are opened for output, so line 12 could have used the alternate statement
ofstream outClientFile( "clients.txt" );
to open clients.txt
for output. Figure 14.4 lists the file-open modes. These modes can also be combined, as we discuss in Section 14.8.
18.217.147.193