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#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// 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 <iostream>
2#include <string>
3#include <fstream> //write and read
4//#include <ifstream> //read
5//#include <ofstream> //write
6
7int main () {
8 std::string line;
9 std::ofstream myfileWrite;
10 std::ifstream myfileRead;
11 myfileWrite.open("example.txt");
12 myfileRead.open("example.txt");
13 myfileWrite << "Writing this to a file.\n";
14 while (getline(myfileRead,line)){
15 std::cout << line << '\n';
16 }
17 myfileWrite.close();
18 myfileRead.close();
19 return 0;
20}
1#include <fstream.h>
2
3void main()
4{
5 ifstream OpenFile("cpp-input.txt");
6 char ch;
7 while(!OpenFile.eof())
8 {
9 OpenFile.get(ch);
10 cout << ch;
11 }
12 OpenFile.close();
13}