1// reading a text file
2#include <iostream>
3#include <fstream>
4#include <string>
5using namespace std;
6
7int main () {
8 string line;
9 ifstream myfile ("example.txt");
10 if (myfile.is_open())
11 {
12 while ( getline (myfile,line) )
13 {
14 //use line here
15 }
16 myfile.close();
17 }
18
19 else cout << "Unable to open file";
20
21 return 0;
22}
1// basic file operations
2#include <iostream>
3#include <fstream>
4using namespace std;
5
6int main () {
7 ofstream myfile;
8 myfile.open ("example.txt");
9 myfile << "Writing this to a file.\n";
10 myfile.close();
11 return 0;
12}
1/ fstream::open / fstream::close
2#include <fstream> // std::fstream
3
4int main () {
5
6 std::fstream fs;
7 fs.open ("test.txt", std::fstream::in | std::fstream::out | std::fstream::app);
8
9 fs << " more lorem ipsum";
10
11 fs.close();
12
13 return 0;
14}
1int a, b;
2
3ifstream bd;
4myfile.open("file.txt");
5
6if (myfile.is_open())
7 while (bd >> a >> b)
8 cout << a << b << endl;
9
10else cout << "ERROR";
1#include <iostream>
2#include <fstream>
3using namespace std;
4int main() {
5 fstream my_file;
6 my_file.open("my_file.txt", ios::in);
7 if (!my_file) {
8 cout << "No such file";
9 }
10 else {
11 char ch;
12
13 while (1) {
14 my_file >> ch;
15 if (my_file.eof())
16 break;
17
18 cout << ch;
19 }
20
21 }
22 my_file.close();
23 return 0;
24}
25