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// io/read-file-sum.cpp - Read integers from file and print sum.
2// Fred Swartz 2003-08-20
3
4#include <iostream>
5#include <iomanip>
6#include <fstream>
7using namespace std;
8
9int main() {
10 int sum = 0;
11 int x;
12 ifstream inFile;
13
14 inFile.open("test.txt");
15 if (!inFile) {
16 cout << "Unable to open file";
17 exit(1); // terminate with error
18 }
19
20 while (inFile >> x) {
21 sum = sum + x;
22 }
23
24 inFile.close();
25 cout << "Sum = " << sum << endl;
26 return 0;
27}
28
1#include <fstream>
2
3ifstream file_variable; //ifstream is for input from plain text files
4file_variable.open("input.txt"); //open input.txt
5
6file_variable.close(); //close the file stream
7/*
8Manually closing a stream is only necessary
9if you want to re-use the same stream variable for a different
10file, or want to switch from input to output on the same file.
11*/
12_____________________________________________________
13//You can also use cin if you have tables like so:
14while (cin >> name >> value)// you can also use the file stream instead of this
15{
16 cout << name << value << endl;
17}
18_____________________________________________________
19//ifstream file_variable; //ifstream is for input from plain text files
20ofstream out_file;
21out_file.open("output.txt");
22
23out_file << "Write this scentence in the file" << endl;
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