Working with Streams 627
17
6: {
7: char fileName[80];
8: char buffer[255];
9: cout << “Please reenter the file name: “;
10: cin >> fileName;
11:
12: ifstream fin(fileName);
13: if (fin) // already exists?
14: {
15: cout << “Current file contents:\n”;
16: char ch;
17: while (fin.get(ch))
18: cout << ch;
19: cout << “\n***End of file contents.***\n”;
20: }
21: fin.close();
22:
23: cout << “\nOpening “ << fileName << “ in append mode...\n”;
24:
25: ofstream fout(fileName,ios::app);
26: if (!fout)
27: {
28: cout << “Unable to open “ << fileName << “ for appending.\n”;
29: return(1);
30: }
31:
32: cout << “\nEnter text for the file: “;
33: cin.ignore(1,’\n’);
34: cin.getline(buffer,255);
35: fout << buffer << “\n”;
36: fout.close();
37:
38: fin.open(fileName); // reassign existing fin object!
39: if (!fin)
40: {
41: cout << “Unable to open “ << fileName << “ for reading.\n”;
42: return(1);
43: }
44: cout << “\nHere’s the contents of the file:\n”;
45: char ch;
46: while (fin.get(ch))
47: cout << ch;
48: cout << “\n***End of file contents.***\n”;
49: fin.close();
50: return 0;
51: }
LISTING17.17 continued