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:

//To write in text mode
fstream out_file {"../file.txt", std::ios::out};

//To write in binary mode
fstream out_file {"../file.txt", std::ios::out|std::ios::binary}

Syntax to create object of ofstream class:

//To write in text mode
ofstream out_file {"file.txt", std::ios::out};
//OR
ofstream out_file {"../file.txt"};

//To write in binary mode
ofstream out_file {"../file.txt", std::ios::out|std::ios::binary};

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:

ofstrean out_file;
std::string filename;

cin >> filename;
out_file.open(filename);

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.

if(out_file.is_open()){     //Or if(out_file)
    //write in File
} else {
    //file could not open file
    //output error
}

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:

if(out_file.is_open()){
    int roll = 77;
    string name = "Krishna";

    out_file << roll << "\n";
    out_file << name << "\n";
}

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:

out_file.close();

C++ Example: Write to the File

#include <iostream>
#include <fstream>
using namespace std;
 
int main()
{
    int roll = 77;
    string name = "Krishna";
    double marks = 100;
 
    //For writing text file
    //Creating ofstream class object
    std::ofstream out_file {"file.txt"};
 
    if(out_file.is_open()){
        cout<<"Using insertion (<<) operator" << endl<<endl;
 
        out_file << roll << "\n";
        out_file << name << "\n";
        out_file << marks << "\n";
 
        cout << "File Writing Successfull \n";
    } else {
        //Something went wrong
        printf("Cannot read File");
    }
 
    //close file
    out_file.close();
 
    return 0;
}

Output:

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

#include <iostream>
#include <fstream>
using namespace std;
 
int main()
{
    string line = "Appending to last";
    //For writing text file
    //Creating ofstream class object for appending
    std::fstream out_file {"file.txt", std::ios::out | std::ios::app};
 
    if(out_file){
        cout<<"Using insertion (<<) operator" << endl<<endl;

        out_file << line ;
 
        cout << "Appending Successfull \n";
    } else {
        //Something went wrong
        printf("Cannot read File");
    }
 
    //close file
    out_file.close();
 
    return 0;
}

Output:

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