Sams Teach Yourself C++ in 21 Days

(singke) #1
On line 7, a buffer is created for the filename, and on line 8, another buffer is set
aside for user input. The user is prompted to enter a filename on line 9, and this
response is written to the fileNamebuffer. On line 12, an ofstreamobject is created,
fout, which is associated with the new filename. This opens the file; if the file already
exists, its contents are thrown away.
On line 13, a string of text is written directly to the file. On line 14, the user is prompted
for input. The newline character left over from the user’s input of the filename is eaten
on line 15 by using the ignore()function you learned about earlier. The user’s input for
the file is stored into bufferon line 16. That input is written to the file along with a
newline character on line 17, and then the file is closed on line 18.
On line 20, the file is reopened, this time in input mode by using the ifstream. The con-
tents are then read one character at a time on lines 23 and 24.

Changing the Default Behavior of ofstreamon Open ..................................


The default behavior upon opening a file is to create the file if it doesn’t yet exist and to
truncate the file (that is, delete all its contents) if it does exist. If you don’t want this
default behavior, you can explicitly provide a second argument to the constructor of your
ofstreamobject.
Valid values for the second argument include


  • ios::app—Appends to the end of existing files rather than truncating them.

  • ios::ate—Places you at the end of the file, but you can write data anywhere in
    the file.

  • ios::trunc—Causes existing files to be truncated; the default.

  • ios::nocreate—If the file does not exist, the open fails.

  • ios::noreplace—If the file does already exist, the open fails.
    Note that appis short for append,ateis short for at end, and truncis short for truncate.
    Listing 17.17 illustrates using append by reopening the file from Listing 17.16 and
    appending to it.


LISTING17.17 Appending to the End of a File
0: //Listing 17.17 Appending to the End of a File
1: #include <fstream>
2: #include <iostream>
3: using namespace std;
4:
5: int main() // returns 1 on error

626 Day 17


ANALYSIS
Free download pdf