Problem: Write a C++ program to create a new text file and write some lines to the same file.
To solve this problem, we will use the fstream library. This library provides the ofstream object that helps in writing to a file in C++.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// create a file object
ofstream outfile;
// open a file named "example.txt" in write mode
outfile.open("example.txt");
// write to the file
outfile << "This is a test." << endl;
outfile << "Writing to a file in C++ is easy." << endl;
// close the file
outfile.close();
// let the user know the file has been created
cout << "File is created and written successfully." << endl;
return 0;
}
Output:
File is created and written successfully.
In the above program, we use the ofstream
object create a new file for writing.
We use open()
method of the ofstream
object to open the file (in this case “example.txt”) in write mode.
Then we use the <<
operator to write to the file, and the endl
manipulator to start a new line after each string.
When we are finished writing to the file, we call the close()
method to close the file.
Finally, we display a message on the screen to let the user know that the file has been created and written to successfully.