File Handling in C++

File Handling in C++ with Examples

In this article, I am going to discuss File Handling in C++ with Examples. Please read our previous article where we discussed Virtual Destructors in C++ with Examples. Files are used to store data in a storage device permanently.

What are Streams in C++?

Before learning File Handling in C++, let us first learn about Streams in C++. A stream is a flow of data or a flow of characters. Streams are used for accessing the data from outside the program that is from external sources or destinations. So, data can be transferred from an external source to a program or from a program to a destination that is an external device. From accessing the data from outside the program we use streams. We can visualize it by the following diagram.

What are Streams in C++?

If we have a program, then the program may be getting the data from the keyboard or program may be sending the data to the monitor or the program may be accessing the data from an external file. The program can read or write data in the file. The program can be accessing the data from the network. So, there are various sources where the program can send and receive the data.

For accessing these sources or getting or sending the data from the program, we use the mechanism of the Streams in C++. So, there are I/O streams that are Input-output streams. For reading the data from the keyboard we use the input stream and for sending the data to the monitor we use the output stream.

And for the file, we need an input-output stream. There are built-in classes available in C++ for accessing the input-output stream. Class iostream is the input-output stream. From ios, the classes are coming out that are istream class for input stream and ostream class for the output stream. For a better understanding, please have a look at the below image.

File Handling in C++ with Examples

Now similarly, for file access also, there are classes available that are ifstream for input stream and ofstream for the output stream.

For input stream from the keyboard, we have already a built-in object present in iostream header file that is cin and also an extraction operator that is “>>”. So directly we can use cin with extraction operator. Cin is an object of istream class. And we have another object that is cout that we commonly used for displaying the text on the screen. cout is an object of ostream. cout is used with the insertion operator “<<”. If you want to print something on the screen then you have to insert your text in cout. So that’s why we use the insertion operator. Similar operators such as insertion and extraction operators are used for files also. So, this is a very easy mechanism provided by C++. And also, we can overload the insertion and extraction operator.

File Writing in C++:

Let us write a program for writing data into a file. For that, we need a header file that is fstream. Please have a look at the below code.

File Writing in C++

Here we have the main function. Suppose we have a file “my.txt” on our computer and we want to write something in the my.txt file. For that, we have written ofstream outfile(“my.txt”). As a constructor, we have mentioned the filename to the object outfile. So, this object outfile will associate with the file my.txt. Now whatever you will write into this outfile object it will get dropped into that file. It’s like you have connected a pipe from your program to that file on the disk. So, whatever you drop in the outfile it will get stored in the file. 

Next thing, when we were opening this file through outfile object, the file should be already existing. If it is existing then outfile will open the file and if it is not existing then it will create a new file with the name my.txt. This is the important thing about the output file or output stream.

Next point, if the already file is existing and it is having some content then what will happen to that content? The outfile will truncate that content or remove the content. Suppose my.txt has some content, my.txt:

100
200
300

So, we have these numbers in the my.txt file. These values will be removed and fresh content will be written. But we don’t want to lose that content so what should we do? If you want to append the new content after the old content then there is a mode available that is ios::app. ‘app’ stands for append. So, we can write like,

ofstream outfile(“my.txt”, ios::app);

In this way, we can add new content to the file without losing the existing content. So like this mode, there are two modes available that are ios::app and ios::trunc. ‘trunc’ stands for truncate.

So if you want to remove the existing content, you can use ios::trunc. By default, the truncate mode is taken otherwise you can mention appending. Here in our example, we don’t want to append, so we don’t write append mode in our program. So outfile is the object associated with my.txt file. We will write the following statement in our main function,

outfile << “Hello” << endl;

This command will insert “Hello” in the my.txt file. Then we will write,

outfile << 25 << endl;

Here 25 will be written in a new line after “Hello”. So, if you want more then you can add more content to the file. Now my.txt file contains,

Hello
23

How to Close the Stream in C++?

After writing the content, you must close the file by writing the following statement.

outfile.close();

This statement will close the stream and the file will be free from the program. It is important to close the file. See sometimes, you have connected a pen drive or memory card to your laptop and you have kept one of the files open and you try to eject the card. Then you will get a message that “some program is using your memory card or pen drive”. So, you cannot eject it. It means the operating system knows that some program is using some file so it will not allow you to eject. It means that files are being occupied or that resource is in use. So, when the program is not used then it should be released. If the program end, then automatically the resource will be released. But if you say file close, then the file should be closed. So, it is a good practice to close the resource when you have finished.

Example to Understand File Handling in C++:

The following example will create a File with the name my.txt (as it is not already existing) and then write three lines of content in it using the C++ File Handling Mechanism. Now, you may have one questions about which location the file is going to be created. It is created in the same location where the project is created. I have created the following project with the name FileHandlingDemo.cpp in D:\Projects\Cpp\FileHandlingDemo location. So, the my.txt file is also going to be generated in the same D:\Projects\Cpp\FileHandlingDemo location.

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ofstream outfile ("my.txt", ios::trunc);
    outfile << "Joy" << endl;
    outfile << 23 << endl;
    outfile << "C++" << endl;
    outfile.close();
}

So, after the execution of this program, we will have a file that is my.txt which has the following content.

Example to Understand File Handling in C++

In the above example, as we are using ios::trunc option, so every time we execute the program, the old content is replaced by the new content. Here, trunc means truncating the old data. Let us see this. Please modify the content as follows:

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ofstream outfile ("my.txt", ios::trunc);
    outfile << "Hellp" << endl;
    outfile << 104 << endl;
    outfile << "Welcome" << endl;
    outfile.close();
}

First, close the opened my.txt file and then run the above code. This time it will not create the my.txt file as this file already exists in the project folder. If you look at the content of the my.txt file, it will remove the old content and add the new content as shown in the below image.

Example to Understand File Handling in C++

Now, if you don’t want to remove the old data instead you want to append the new data below the old data, then you need to use the ios::app option as shown in the below example.

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ofstream outfile ("my.txt", ios::trunc);
    outfile << "Hi" << endl;
    outfile << 105 << endl;
    outfile << "Bye" << endl;
    outfile.close();
}

Now, close the opened my.txt file and then run the above code and you will see that the new data is appended below the old data as shown in the below image.

File Writing in C++

File Reading in C++:

Now, we will write a program for reading the data from the files using C++ Language. Let’s say we have a file called my.txt with the following content in it in the same location where we created the project i.e. FileHandlingDemo.cpp.

File Reading in C++

We want to read the content from the above my.txt file. So let us see how to read the data from a file in C++ Language.

How to Open a File in C++?

Before reading the content of a file, we must first open that file. Please have a look at the following code.

How to Open a File in C++?

Here we have written some code. Let us understand this step by step. Inside the main function, we have taken the ifstream object infile. Here we have just declared the object not mentioned in the file. Now we will see the other methods of opening a file.

Next, we use the open function to open the file my.txt. And we are using input file input stream so we are making it for reading purposes only. If you want to open the file for writing or reading purposes, there are some modes that are ios::in for reading the file and ios::out for writing in the file. These modes are also known as flags. By default, the open function will use read mode. So, we don’t want to mention any flag or mode there.

So, infile.open(“my.txt”) statement will open the file. Now one important thing, when you are reading from a file then the file must be existing. It will not create a new file so the file must be existing at the location where the program is saved. So, we have to check whether the file has opened or not. Next, we have checked for the file status. if(!infile) statement will check for whether the file is open or not. This condition will be true only if the file is not open. So, inside the if condition we can write the print statement “file cannot be opened”. 

There is another method for checking the file status. infile.is_open(), this method will return true if the file is opened otherwise it will return false. So, this is how you can check whether the file is open or not. Usually when you try to open some file then we get a prompt that the file is not existing or some other messages we get. So, like this only we have to check whether the file is open or not. For a better understanding, please have a look at the below example.

How to Read the content of a File in C++?

Now we want to read the content from the files. So, for that, the code is as follows:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ifstream infile;
    infile.open("my.txt");

    string str;
    int x;

    infile >> str;
    infile >> x;
    cout << str << " " << x;

    if (infile.eof())
        cout << "end of file reached";
    infile.close ();
}

Let us understand this step by step.

So, for reading the values from the files, we have taken two variables: str of type string and x of type int. We want to read from the files so we have used the extraction operator. infile >> str, this will read the first value that is ‘Joy’. On the next line, we have written, infile >> x. This will read the second value which is 104. So, the first value is a string and the second value is an integer. On the next line, we have printed these values. 

So, we have extracted the values from the file in the program and printed those values on the screen. With the help of infile object, we have read the values from the file. That’s all.

What is eof function in C++?

One important thing, once we have finished reading the content, we have reached the end of the file (eof). So sometimes we need to check whether we have reached the end or not. There is a function available that will return true if we are at the end otherwise false. infile.eof(), this statement will return true if we are at the end of the file. So, we have written the print statement “end of file reached”. 

Then at the last, we closed the file by writing infile.close(). So that’s all.

Note: We have learned how to write the data in the file and how to read the data from the file. Now one important thing, when we are reading the data from the file, we should already know in which order that data is present in the file. Then only we can read the data in the same form. So, there is some predefined order of writing the data available like a jpg file. So, there is some known order. So that’s why we say File Format. So, if data is written in the known format then only the programs can read the data in that particular format and show you the contents. Like jpg file can be opened anywhere. If you know the format then you can read the data. If you want to read the jpg file and display the image in your program then you should know the format of jpg files. Likewise, for pdf, you should know the format of pdf. 

Example to Understand File Reading in C++:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ifstream ifs;
    ifs.open ("my.txt");
    if (ifs.is_open())
        cout << "File is Opened" << endl;
        
    string name;
    int roll;
    string branch;
    ifs >> name >> roll >> branch;
    ifs.close();
    
    cout << "Name: " << name << endl;
    cout << "Roll: " << roll << endl;
    cout << "Branch: " << branch << endl;

    if(ifs.eof())
        cout << "End of File Reached";
}
Output:

Example to Understand File Reading in C++

In the next article, I am going to discuss Serialization in C++ with Examples. Here, in this article, I try to explain File Handling in C++ with Examples and I hope you enjoy this File Handling in C++ with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this File Handling in C++ with Examples article.

Leave a Reply

Your email address will not be published.