Table of Contents
Back Button
Back to Chapter
No items found.

C++ File Handling

While writing real-world applications we need the application to store data once we use the application, also it should allow us to modify this data as and when we wish to do so.

So far, we have been using the iostream standard library, which provides us with cin and cout methods for reading from standard input and writing to standard output respectively.

Files are used to store data in a storage device permanently. File handling provides a mechanism to store the output of a program in a file and perform various operations on it.

In C++ we have a set of file handling functions. These are ifstream, ofstream, and fstream. These classes are derived from fstreambase and from the corresponding iostream class. These classes, designed to manage the disk files, and are declared in fstream, therefore we must include fstream in every program that uses files.

  • ofstream: This Stream class signifies the output file stream and is applied to create files to write information to files
  • ifstream: This Stream class signifies the input file stream and is applied to read information from files
  • fstream: This Stream class can be used to both  read from and write to  files.

C++ offers us the following operations in File Handling:

  • open():Creating a file
  • read():**Reading data
  • write():Writing new data
  • close():Closing a file

Lets us look into each of these functions in detail and see how we can implement them.

Opening a file

Usually, the first operation performed on an object of one of these classes is to associate it to a real file. This procedure is known as opening a file.

We can open a file using one of the following methods:

  1. bypassing the file name in constructor at the time of object creation.
  2. using the open() function.

Syntax to open a file

void open(const char* fileName,ios::openMode mode);

The first argument of the open function is the name and format of the file along with the address of the file.

The second argument represents the mode in which the file has to be opened.

The following modes can be used as per our requirement.


fstream newFile;"newfile.txt", ios::out);

Default Open Modes :

  • ifstream: ios::in
  • ofstream: ios::out
  • fstream: ios::in | ios::out

We can combine the different modes using or symbol | .


fstream newFile2;"newfile2.txt",ios::out|ios::app);

Input mode and append mode are combined which means the file is opened for writing and appending the outputs at the end.

C++ code Demonstrating of opening and closing a file.

#include #include using namespace std; int main() { fstream newFile;"newfile.txt",ios::out); //creating a file if(!newFile) { cout<<"File creation failed"; } else { cout<<"New file created"; newFile.close(); // closing the file } return 0; }
Output: New file created

In the above example first, we created an object to class fstream and named it ‘newFile’. Then we used the open() function on our ‘newFile’ object. We give the name ‘newfile’ to the new file we wanted to create and we set the mode to out which allowed us to write in our file. We use an if statement to find if the file already exists or not if it does exist then it is going to print “File creation failed” else it will create a new file and print “New file created”.

Writing to a file

First create a new file “new_filewrite” using open() function as we want to send output to the file  we use ios::out. The information we type inside the quotes after Insertion Pointer “<<” gets passed to the output file.

Example demonstrating how to write data into a file.

#include #include using namespace std; int main() { fstream newFile;"new_filewrite.txt",ios::out); if(!newFile) { cout<<"File creation failed"; } else { cout<<"New file created"; newFile<<"LEARN FILE HANDLING"; //Writing to file newFile.close(); } return 0; }
Output: New file created

Reading from the file

We read the file that is generated in the previous example i.e. new_filewrite.

To read a file we make use of the in mode with syntax ios::in. We print the content of the file using extraction operator `>>`. The output prints without any space because we use only one character at a time, we need to use getline() with a character array to print the whole line as it is.

#include #include using namespace std; int main() { fstream newFile;"new_filewrite.txt",ios::in); if(!newFile) { cout<<"No such file"; } else { char ch; while (!newFile.eof()) { newFile >>ch; cout << ch; } newFile.close(); } return 0; }

Closing a file

Once we are done using a file in a C++ program use the close() function to close the file.

#include #include using namespace std; int main() { fstream newFile;"newFile.txt",ios::out); newFile.close(); return 0; }

The file gets closed!!

Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?