xxxxxxxxxx
#include <fstream>
int main()
{
// ofstream = output file stream
std::ofstream stream("example.txt"); // Open
if (!stream)
return 1; // Error while opening file!
stream << "Some text here"; // Write
return 0;
} // The file is automatically closed by the destructor.
xxxxxxxxxx
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
string fileName;
int choice;
cout << "Enter txt file name:\n";
cin >> fileName;
cout << "Enter number of command:\n";
cout << "1. Write file\n";
cout << "2. Read file\n";
cin >> choice;
if (choice == 1)
{
ofstream myfile;
string text;
myfile.open (fileName);
cout << "Write text below: \n"; //file must have no text
cin >> text;
myfile << text;
myfile.close();
}else if (choice == 2)
{
ifstream file(fileName);
string line;
if (file.is_open())
{
while (getline(file, line))
{
cout << line << endl;
}
}
}
return 0;
}