To write in a file in C++, two file stream classes are commonly used:

  • fstream
  • ofstream

First, we need to include these class in our program.

Then we need to create an object of either of two classes.

Or we can create an object of ofstream class to write in file.

In the above example of creating a file stream object, we have already assumed that we have to know the name of the file. In case we want the user to input the file name, then we can manually add file name to the stream object using open() method.

After connecting the file stream object to the file, we then need to check whether the file has successfully opened or not. For this we use is_open() function.

Note: The file should be present int he same directory where the program executable file is, If not then file will automatically be created.

Now to write in file we use insertion (<<) operator, similarly as we use it with cout.

Example 1: Write in File in C++


Write in File in C++

C++ Program to write in File

Output of write in File C++ Program

Example 2: Write in File in C++


Write in File C++

Output of Write in File

Append to file in C++

On using above method our file always gets truncated or overwritten. If we want to append to file without deleting its previous content, we need to use file stream in append mode by using std::ios::app.

C++ Program to Append to File


Append to file in C++

Output of Append to file in C++

Always close file using close() method after completing all file operations to flush unwritten data. That’s all we need to know in order to write in file in C++. If you have any doubt then comment in the comment section.

Leave a Reply