Please reenter the file name: test1
Current file contents:
This line written directly to the file...
This text is written to the file!
***End of file contents.***
Opening test1 in append mode...
Enter text for the file: More text for the file!
Here’s the contents of the file:
This line written directly to the file...
This text is written to the file!
More text for the file!
***End of file contents.***
Like the preceding listing, the user is again prompted to enter the filename on
lines 9 and 10. This time, an input file stream object is created on line 12. That
open is tested on line 13, and if the file already exists, its contents are printed on lines
15–19. Note that if(fin)is synonymous with if (fin.good()).
The input file is then closed, and the same file is reopened, this time in append mode, on
line 25. After this open (and every open), the file is tested to ensure that the file was
opened properly. Note that if(!fout)is the same as testing if (fout.fail()). If the
file didn’t open, an error message is printed on line 28 and the program ends with the
returnstatement. If the open is successful, the user is then prompted to enter text, and
the file is closed again on line 36.
Finally, as in Listing 17.16, the file is reopened in read mode; however, this time fin
does not need to be redeclared. It is just reassigned to the same filename. Again, the open
is tested, on line 39, and if all is well, the contents of the file are printed to the screen
and the file is closed for the final time.
OUTPUT
628 Day 17
ANALYSIS
DOtest each open of a file to ensure
that it opened successfully.
DOreuse existing ifstreamand ofstream
objects.
DOclose all fstreamobjects when you
are done using them.
DON’Ttry to close or reassign cinor
cout.
DON’T use printf()in your C++
programs if you don’t need to.
DO DON’T