C++ File Handling – A Quick Overview

Filed Under: C++
File Handling In C

In this article, we will learn the concept of File Handling In C++. We will also be going through an example file handling code.

File Handling is the practice that involves reading and modifying files by the means of computer programs written to perform a specific task.

Why Do We Need File Handling?

The simple answer to this question lies in the fact that almost every digital activity we do involves file handling. Though there can be countless use-cases, let’s consider the following examples:

  • All the Official Documents related to either large Organizations or Personal Computer are stored and accessed using the concept of file handling.
  • File Managers and File Systems use the concept of File handling to strore all the information and various system applications
  • Version Control Systems like Git, GitLab, etc
  • Working of Operating Systems
  • Creating Large Projects and Applications like:
    • Office Suites
    • IDEs
    • Games
    • Cloud Storage
  • Cameras: To manage the pictures and videos.

In the digital era it’s next to impossible to find, activities not involving file handling.

File Handling In C++ Programs

Let’s learn to work with files in C++. Don’t worry it’s very simple yet effective

1. File Modes

Firstly, let’s learn about different file modes to open a file in your C++ program. Most of the time we tend to use the modes mentioned below to open a file.

  1. in: Open for reading
  2. out: Open for writing
  3. ate: Seek to the end of file upon original open
  4. app: Append mode

These modes define the access available to the user. If a file is opened in “reading” mode, then write operations can not be performed on this file until it is opened in “writing” mode.

Similarly, one can not get the contents of the file if it is opened in “writing” mode, because this mode allows only writing operations to be done on the file. Without wasting any more time let’s quickly jump to the code so that everything becomes crystal clear.

2. File Operations In C++

We use the “fstream” library of C++ to deal with operations involving files.

This fstream library provides us with four elementary operations for file handling. These operations are:

1. open(): Creates a file

open("file_name_without_quotes", file_mode);

2. read(): Reads the contents of a file

The “>>” operator is overloaded for reading the contents of a file, hence the read operation can simply be done using the following syntax:

File_Handler >> Variable_To_Store_the_Content;

3. write(): Write some data to the file

Similar to the reading operation, the “<<” operator is overloaded for writing data to files

File_Handler << Variable_That_Contains_The_Data_To_Be_Written;

4. close(): Used to safely close the handle to the file

Note: It’s a healthy practice to “close” the handler to the file. Because it prevents the chances of data loss.

File_Handler.close();

Complete C++ Program for File Handling

For ease of understanding, we will consider a simple C++ program that reads the data written in a file and displays it at the output.

Code

#include <iostream>
#include <stdlib.h>
#include <fstream>

using namespace std;

int main(int argc, char **argv)
{
        if(argc < 2)
        {
                cout << "Please Provide The Input File !!! Aborting !!!" << endl;
                exit(0);
        }

        cout << "The name of the file is: " << argv[1] << endl;

        fstream file_handler;
        file_handler.open(argv[1], ios::in);

        if(!file_handler)
        {
                cout<<"This File doesn’t exist.";
        }
        else
        {
                char data;
                while(true)
                {
                        file_handler >> data;
                        if(file_handler.eof())
                                break;
                        cout << data;
                }
        }
        cout << endl;

        file_handler.close();
}

File Handling Progam
File Handling Progam

Output

We’ll give our code file as input here. Let’s now run our code to read the data stored in this file

Output
Output

Conclusion

In this article, we learned the basic concepts of File Handling. We also discussed different types of file modes, further, we learned about the basic functions of the fstream class. We also considered a C++ program to read the contents of a file

References

To learn more about file handling, you can refer to the following websites:

https://en.cppreference.com/w/cpp/io/basic_fstream

https://www.cplusplus.com/reference/fstream/fstream/

close
Generic selectors
Exact matches only
Search in title
Search in content