c++ fstream code example
Example 1: fstream in c++
#include<fstream>
int main()
{
fstream file;
file.open("filename.txt", ios::out|ios::in);
file.close();
return 0;
}
Example 2: 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 3: 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 4: read text from file c++
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream myReadFile;
myReadFile.open("text.txt");
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
cout<<output;
}
}
myReadFile.close();
return 0;
}
Example 5: write to file in C++
ofstream myfile;
myfile.open("file.txt");
myfile << "write this to file"