11. File Input/Output (Header <fstream>)
The <fstream> header provides ifstream (input file stream) and ofstream (output file stream) for file input and output.
The steps for file input/output are:
- Create a ifstream for input, or ofstream for output.
- Connect the stream to an input or output file via open(filename).
- Perform formatted output via stream insertion operator <<, or input via stream extraction operator >>, similar to cout << and cin >>.
- Close the file and free the stream.
11.1 Example: File IO1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| /* Test File I/O (TestFileIO.cpp)
Read all the integers from an input file and
write the average to an output file */
#include <iostream>
#include <fstream> // file stream
#include <cstdlib>
using namespace std;
int main() {
ifstream fin; // Input stream
ofstream fout; // Output stream
// Try opening the input file
fin.open("in.txt");
if (!fin.is_open()) {
cerr << "error: open input file failed" << endl;
abort(); // Abnormally terminate the program (in <cstdlib>)
}
int sum = 0, number, count = 0;
while (!(fin.eof())) {
// Use >> to read
fin >> number;
sum += number;
++count;
}
double average = double(sum) / count;
cout << "Count = " << count << " average = " << average << endl;
fin.close();
// Try opening the output file
fout.open("out.txt");
if (!fout.is_open()) {
cerr << "error: open output file failed" << endl;
abort();
}
// Write the average to the output file using <<
fout << average;
fout.close();
return 0;
}
| Input File: in.txt
12 15 35 26 68
Output File: out.txt
31.20
Program Notes:
- Once the file is opened, you can use >> and << for input and output, similar to cin >> and cout <<. (Advanced note: ifstream is a subclass of istream, where cin belongs. ofstream is a subclass of ostream, where cout belongs.)
- Similarly, IO manipulators, such as fixed, setprecision() and setw(), work on the file streams.
11.2 Exercises
[TODO]
|