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;