Write a File using C++ fstream
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 ( << ).
- Include the Header file ostream
- declare a variable of type ofstream.
- Open the file for writing.
- check for an open file error.
- use the file.
- Write the Statement.
- Run the Program.
- close the open file.
This C++ program demonstrates how to write a file using fstream.
- First, the #include directive is used to include the required input/output library header files, iostream and fstream.
- In the main() function, we create an ofstream object called o and pass the filename test.txt to its constructor. We also specify the mode in which we want to open the file using the ios::trunc flag, which means that if the file already exists, its contents will be truncated before writing to it.
- Then we write some text to the file using the << operator and close the file using the close() function.
- When we run the program, it will create a new file called test.txt if it does not already exist in the same directory as the program. If the file already exists, its contents will be overwritten with the new text we write to it.
Source Code
#include<iostream>
#include<fstream>
using namespace std;
//Write a File using C++ fstream
int main()
{
ofstream o("test.txt",ios::trunc);//ios::app
o<<"Tutor Joes Computer Education,"<<endl;
o<<"Cherry Road."<<endl;
o<<"Salem."<<endl;
o<<"Tutor Joes Stanley."<<endl;
o.close();
return 0;
}
To download raw file
Click Here
Output
Before Write File
After Write File