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<fstream>
2int main()
3{
4 fstream file;
5 /*if we use fstream then we need to specify at least one
6 parameter mode like ios::out or ios::in else the file will not open */
7 file.open("filename.txt", ios::out|ios::in);
8 /*all work with file*/
9 file.close();
10 return 0;
11}
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