create a file c++ code example
Example 1: read a file c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Example 2: create new file c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream MyFile("filename.txt");
MyFile << "Files can be tricky, but it is fun enough!";
MyFile.close();
Example 3: create file c++
#include <iostream>
#include <fstream>
std::ofstream outfile ("test.txt");
outfile << "my text here!" << std::endl;
outfile.close();