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#include <iostream>
2#include <fstream>
3using namespace std;
4
5ifstream file_variable; //ifstream is for input from plain text files
6file_variable.open("input.txt"); //open input.txt
7
8file_variable.close(); //close the file stream
9/*
10Manually closing a stream is only necessary
11if you want to re-use the same stream variable for a different
12file, or want to switch from input to output on the same file.
13*/
14_____________________________________________________
15//You can also use cin if you have tables like so:
16while (cin >> name >> value)// you can also use the file stream instead of this
17{
18 cout << name << value << endl;
19}
20_____________________________________________________
21//ifstream file_variable; //ifstream is for input from plain text files
22ofstream out_file;
23out_file.open("output.txt");
24
25out_file << "Write this scentence in the file" << endl;
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}