To create a file, use either the ofstream
or fstream
class, and specify the name of the file.
To write to the file, use the insertion operator (<<
).
Example
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!";
// Close the file
MyFile.close();
}
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!";
// Close the file
MyFile.close();
}
Why do we close the file?
It is considered good practice, and it can clean up unnecessary memory space.
Practice Excercise Practice now