Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconImportance of File Handling in C++ & How To Do It [2024]

Importance of File Handling in C++ & How To Do It [2024]

Last updated:
26th Jun, 2023
Read Time
9 Mins
share image icon
In this article
Chevron in toc
View All
Importance of File Handling in C++ & How To Do It [2024]


C++ or ‘the New C,’ as it is based on C’s framework and additional features. C++ is also credited to influence several languages such as C# and other newer editions of C. It is also recognized with the introduction of Object-Oriented Programming. This establishes the fact about how essential C++ has been for the programming world. 

This article is about one of the most basic yet crucial tasks, file handing in C++. Now, files are significant for programming as well as for other sectors as they are the storage sectors. This is where the entire data is assembled. The whole concept of file handling can be divided into four sections – 

  • Opening a File
  • Writing to a File
  • Reading from a File
  • Close a file

Check out our free courses to get an edge over the competition.

Get Software Development Course from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Ads of upGrad blog

Importance of File Handling in C++

Before we embark on this journey of C++, let’s take a few moments to understand why do we need file handling. In simple terms, it offers a mechanism through which you can collect the output of a program in a file and then perform multiple operations on it. 

There is one more term, “Stream,” which we’ll be using quite frequently. So, let’s get acquainted with it, as well. A stream is a process that indicates a device on which you are performing the input and output operations. In other words, the stream can be represented as an origin or target of characters of unspecified length based on its function. 

Check out upGrad’s Java Bootcamp

ifstream, ofstream, and fstream make the set of file handling methods in C++. A brief description of these three objects –

  • ofstream – In C++, ofstream is used to create and write in files. It signifies the output file stream. 
  • ifstream – Programmers use ifstream to read from files. It signifies the input file stream. 
  • fstream – fstream can be said as a combination of ofstream and ifstream. It is used to create, read, and write files.

Each one of them helps to manage disk files and, therefore, is specifically designed to manage disk files.

These are the operations used in File Handling in C++  – 

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

Must Read: Top 8 Project Ideas in C++

Let’s discuss them thoroughly to understand how file handling in C++ works –

  • Opening a File

Before you can take action on the file, be it read or write, you need to open it first. Ofstream or fstream objects can be applied to initiate a file for writing. Similarly, the ifstream object can be used if you want to read the file. 

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

You can use the following procedures to open a file – 

  • At the time of object creation, bypass the file name. 
  • Or you can use the open() function. It is a member if ifstream, ofstream, fstream objects.

For example 

void open(const char *nameofthefile, ios::openmode mode);

The first argument in the above defines the name and location of the file which you want to open. The second argument specifies the method by which your target file should be opened. 

Here are the Mode Flag & Description –

  1. ios::app – Append mode. All output to that file to be attached to the end.
  2. ios::in – Open a file for reading. 
  3. ios::ate – Open a file for output and move the read/write control to the end of the file.
  4. ios::out – Open a file for writing. 
  5. ios::trunc – If the file already exists, its contents will be truncated before opening the file.

You can create multiple values using the above modes by using the OR. For instance, if you wish to open a file for reading or writing purpose, use-

fstream newfile; ("file.dat", ios::out | ios::in );
Similarly, if you wish to open a file in write mode and wish to truncate it if it already exists -
ofstream newfile; ("file.dat", ios::out | ios::trunc );

Explore our Popular Software Engineering Courses

  • Writing a file 

While working on a C++ programming file, use either ofstream or fstream object along with the name of the file. It would be best to use the stream insertion operator (<<) to write information to a file. 

#include <iostream>
#include <fstream>
Utilize namespace std; 
int main() {
  // Create and open a text file
  ofstream newFile("filename.txt");
  // Write to the file
  NewFile << "Learning files can be challenging, but the result is satisfying enough!";
  // Close the file

  • Reading a file

For reading a C++ programming file, you use either the fstream or ifstream object. In case you want to read the file line by line, and to print the content of the file, use a while loop along with the getline () function. 

To read information from a file, you need to use the stream extraction operator (>>). 


// Construct a text string, which is managed to output the text file
string newText;
// Read from the text file
ifstream newReadFile("filename.txt");
// Now use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
  // Output the text from the file
  cout << myText;
// Close the file

In-Demand Software Development Skills

  • Closing a file 

By default, when a C++ program closes, it expels all the teams, lets out all the designated memory, and concludes all the opened files. But it is considered to be a healthy practice in terms of file handling in C++ that one should close all the opened files prior to the termination of the program. It also cleans up unnecessary space.

This is the standard syntax for close() function. It is a member of fstream, ifstream, and ofstream objects.

void close();

Also Read: Data Structure Project Ideas

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

File Position Pointers

Once you understand the different aspects of file handling in C plus plus, you should know about the file position pointers. A file position pointer refers to a specific index inside a file where write or read operations are present. You will come across get and put pointers in C++.

You can use the associated functions tellg() and tellp(0 to locate the position of these pointers. You can also modify the position of the pointer with the functions seekg() and seekp(). Here, you will be able to read or write after changing a specific position. Methods like seekp() and seekg() follow parameters like long integers and seek directions.

Some common examples include:

  • Ios::beg (for positioning before a stream)
  • Ios::cur (for positioning relative to the present position of a stream)
  • Ios::end (for positioning at a stream’s end)

tellp() and tellg() 

tellp() can return the current position of the put pointer, which is employed with output streams while data is written to the file. tellg() can return the present position of the get pointer, which is employed alongside input streams while receiving data from the file. 


#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream file;
    // Open file in write mode."myfile.txt", ios::out);
    cout << "Position of put pointer before writing:" << file.tellp() << endl;
    file << "Hello Everyone"; // Write on file.
    cout << "Position of put pointer after writing:" << file.tellp() << endl;
    ifstream file1;"myfile.txt", ios::in); // Open file in read mode.
    cout << "Position of get pointer before reading:" << file1.tellg() << endl;
    int iter = 5;
    while (iter--) {
        char ch;
        file1 >> ch; // Read from file.
        cout << ch;
    cout << endl << "Position of get pointer after reading:" << file1.tellg();


Position of put pointer before writing:0
Position of put pointer after writing:14
Position of get pointer before reading:0
Position of get pointer after reading:5

seekg() and seekp()

The function istream& seekg (streampos pos) can return the istream object by modifying the position of the get pointer to pos. istream& seekp (streampos pos) is the function that can return the ostream object by modifying the position of the put pointer. 

Ads of upGrad blog


#include <fstream>
#include <iostream>
using namespace std;
int main() {
    fstream myFile("myfile.txt", ios::out);
    myFile << "123456789";
    myFile.close();"myfile.txt", ios::in);
    std::string myline;
        while (myFile.good()) {
            std::getline (myFile, myline);
            std::cout << myline << std::endl;



Explore Our Software Development Free Courses


That concluded the lesson on ways in which you can do file handling in C++. Remember, C++ is one of the most predominant languages in the programming world to create both technical and commercial softwares.

Therefore, the more you understand, the more you can explore using this versatile language.If you are interested to learn more and need mentorship from industry experts, check out upGrad & IIIT Banglore’s Executive PG Program Full-Stack Software Development.


Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1What is File handling in C++?

File handling refers to the process of storing files with the help of programming languages and codes. A stream is a type of concept that describes a device that performs input and output actions. Depending on its use, a stream can be represented as a source or destination of indefinitely long characters. We have a collection of file handling functions in C++. ifstream, ofstream, and fstream are some examples of these streams. These components are developed from fstrembase and its iostream counterpart. These classes, which are used to manage disc files, are declared in fstream. Thus we must include fstream in any application that uses files.

2What is C++?

C++ is a general-purpose programming language that programmers may use for a variety of purposes. Programmers can use it to make operating systems, browsers, games, and other programs. It can handle a wide range of programming techniques, including procedural, object-oriented, and functional. So, this makes C++ a really powerful and versatile programming language. It's a compiled, general-purpose, statically typed, and case-sensitive programming language with no restrictions. All types of programming are supported, including procedural, object-oriented, and generic. It comes with an extensive standard library that includes, among other things, a significant number of methods for managing files and ways to manipulate data structures. C++ is widely used by programmers and developers, especially in the application development industry.

3How can we differentiate between C and C++?

C++ is a specialized version of C, and programmers can perform most C programs in C++ with a few changes. C is a procedural language, but C++ lets you write both procedural and object-oriented code. As an object-oriented programming language, C++ has capabilities such as method overloading, frames, inheritance, virtual functions, and other activities. C does not have these properties. In C++, exception management is supported at the language level, whereas in C, exception management is done using the if-else method. In C++, references are supported, but not in C. In C, the input/output functions scanf() and printf() are utilized. Streams are used primarily for input and output operations in C++.