Reading to files and from files C++ code example
Example 1: opening file in c++
/ fstream::open / fstream::close
#include <fstream>
int main () {
std::fstream fs;
fs.open ("test.txt", std::fstream::in | std::fstream::out | std::fstream::app);
fs << " more lorem ipsum";
fs.close();
return 0;
}
Example 2: How to read a file in in C++
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() {
int sum = 0;
int x;
ifstream inFile;
inFile.open("test.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1);
}
while (inFile >> x) {
sum = sum + x;
}
inFile.close();
cout << "Sum = " << sum << endl;
return 0;
}
Example 3: write to file in C++
ofstream myfile;
myfile.open("file.txt");
myfile << "write this to file"