Summary: In this tutorial, we will learn to write to a file using the stream classes in C++.

Output File Stream Class

The fstream library provides the following two classes to write file in C++:

  • fstream: File stream class used both for reading and writing to a file.
  • ofstream: Output stream class used for writing data to the files.

To write in a file, we start by creating objects of any of these classes.

Syntax to create object of fstream class:

Syntax to create object of ofstream class:

In case the user has to input the name of the file, we can use the open() method to initialize the output file stream object:

Write Data to the File

Till now we have connected the target file to the output stream object. But we have to be sure that it succeeded to avoid any exceptions. For this, we use the is_open() method on the stream object.

The is_open() method returns true if the file is connected with the stream object, otherwise it returns false.

Note: The target file and the executable program file must be in the same directory otherwise a new file of the same name will automatically be created.

Once the file is connected, we can proceed to write data to the same.

We use the insertion (<<) operator to write formatted data to the file.

Here is an snippet, where we are writing int and string data to a file:

Close File After Writing

It it always recommended to close the file to flush the inwritten data when the reading or writing process is complete.

To close a file we invoke the close() method on the stream object:

C++ Example: Write to the File


Write in File in C++
C++ Program to write in File
Output of write in File C++ Program

Append Data to the file

Whenever we write data to a file, its old contents gets truncated.

If we want to attach new data to a file without deleting its old content, we need to use the file stream in extend mode and we can easily do that using the std::ios::app argument.

C++ Example: Append to the File


Append to file in C++
Output of Append to file in C++

In this tutorial, we learned how to write and append to a text file in the C++ programming language.

Leave a Reply

9 − 4 =