Opening a File

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

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.