Working with files in C++ requires the following steps:
<fstream>
header file>>
or <<
#include <fstream>
.open()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("myfile.txt");
if (!fin.is_open()) {
cout << "Could not open file myfile.txt\n";
}
int data;
fin >> data;
cout << "File contained integer: " << data << '\n';
fin.close();
}
.fail()
.is_open()
.close()
>>
1
2
3
4
5
6
ifstream fin;
int a, b, c;
fin.open("myfile.txt");
fin >> a >> b >> c; // Extract 3 integers from file.
cout << "I got three integers: " << a << ' ' << b << ' ' << c;
fin.close();
fin >>
will skip preceding whitespace and extract until the next whitespace.getline()
.getline(fin, line)
\n
’
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin;
string line;
fin.open("myfile.txt");
while (getline(fin, line)) {
cout << "Line = " << line << '\n';
}
fin.close();
return 0;
}
iomanip
!
1
2
3
4
5
6
7
ofstream fout;
int i = 10;
double j = 22.7124;
fout.open("myfile.txt"); // creates or overwrites myfile.txt
fout << left << setw(10) << i << ' ' << fixed << setprecision(2)
<< j << '\n';
fout.close();
1
'myfile.txt' now contains: "10 22.71"
1
2
3
4
ofstream fout;
fout.open("myfile.txt");
// ... do things with fout ...
fout.close(); // do this!!