fstream and File Open Modes in C++

You can use fstream to create a file object for both input and output

In the preceding sections, you used the ofstream to write data and the ifstream to read data. Alternatively, you can use the fstream class to create an input or output stream. It is convenient to use fstream if your program needs to use the same stream object for both input and output. To open an fstream file, you have to specify a file open mode to tell C++ how the file will be used. The file modes are listed in Table 13.1.

Listing 13.8 gives a program that creates a new file named city.txt (line 11) and writes data to the file. The program then closes the file and reopens it to append new data (line 19), rather than overriding it. Finally, the program reads all data from the file.

Listing 13.8 AppendFile.cpp

1 #include <iostream>
2
#include <fstream>
3
#include <string>
4
using namespace std;
5
6
int main()
7 {
8     fstream inout;
9
10   
// Create a file
11    inout.open(“city.txt”, ios::out);
12
13   
// Write cities
14    inout << “Dallas” << ” ” << “Houston” << ” ” << “Atlanta” << ” “;
15
16    inout.close();
17
18   
// Append to the file
19    inout.open(“city.txt”, ios::out | ios::app);
20
21   
// Write cities
22    inout << “Savannah” << ” ” << “Austin” << ” ” << “Chicago”;
23
24    inout.close();
25
26    string city;
27
28   
// Open the file
29    inout.open(“city.txt”, ios::in);
30   
while (!inout.eof()) // Continue if not end of file
31    {
32        inout >> city;
33        cout << city <<
” “;
34    }
35
36    inout.close();
37
38   
return 0;
39 }

The program creates an fstream object in line 8 and opens the file city.txt for output using the file mode ios::out in line 11. After writing data in line 14, the program closes the stream in line 16.

The program uses the same stream object to reopen the text file with the combined modes ios::out | ios::appin line 19. The program then appends new data to the end of the file in line 22 and closes the stream in line 24.

Finally, the program uses the same stream object to reopen the text file with the input mode ios::in in line 29. The program then reads all data from the file (lines 30-34).

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *