Working with Streams 625
17
One important file stream function that you will need right away is close(). Every file
stream object you create opens a file for reading (input), writing (output), or both. It is
important to close()the file after you finish reading or writing; this ensures that the file
won’t be corrupted and that the data you’ve written is flushed to the disk.
After the stream objects are associated with files, they can be used the same as any other
stream objects. Listing 17.16 illustrates this.
LISTING17.16 Opening Files for Read and Write
0: //Listing 17.16 Opening Files for Read and Write
1: #include <fstream>
2: #include <iostream>
3: using namespace std;
4:
5: int main()
6: {
7: char fileName[80];
8: char buffer[255]; // for user input
9: cout << “File name: “;
10: cin >> fileName;
11:
12: ofstream fout(fileName); // open for writing
13: fout << “This line written directly to the file...\n”;
14: cout << “Enter text for the file: “;
15: cin.ignore(1,’\n’); // eat the newline after the file name
16: cin.getline(buffer,255); // get the user’s input
17: fout << buffer << “\n”; // and write it to the file
18: fout.close(); // close the file, ready for reopen
19:
20: ifstream fin(fileName); // reopen for reading
21: cout << “Here’s the contents of the file:\n”;
22: char ch;
23: while (fin.get(ch))
24: cout << ch;
25:
26: cout << “\n***End of file contents.***\n”;
27:
28: fin.close(); // always pays to be tidy
29: return 0;
30: }
File name: test1
Enter text for the file: This text is written to the file!
Here’s the contents of the file:
This line written directly to the file...
This text is written to the file!
***End of file contents.***
OUTPUT