Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

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

Updated on 20 December, 2023

9.03K+ views
9 min read

Introduction

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.

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; 
newfile.open ("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; 
newfile.open ("file.dat", ios::out | ios::trunc );
  • 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
  NewFile.close();
}
  • 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 (>>). 

Example 

// 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
MyReadFile.close();
  • 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. 

Example:

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ofstream file;
    // Open file in write mode.
    file.open("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;
    file.close();
    ifstream file1;
    file1.open("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();
    file1.close();
}

Output:

Position of put pointer before writing:0
Position of put pointer after writing:14
Position of get pointer before reading:0
Hello
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. 

Example:

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

Output:

45*789

Conclusion 

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.

Frequently Asked Questions (FAQs)

1. What 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.

2. What 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.

3. How 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++.

RELATED PROGRAMS