Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is File Handling in C++?
2.1.
fstream Library
2.2.
ifstream
2.3.
ofstream
3.
File operations in C++
3.1.
Opening a File
3.1.1.
Syntax
3.1.2.
Example
3.2.
C++
3.2.1.
Output
3.2.2.
Explanation
3.3.
Writing a File
3.3.1.
Syntax
3.3.2.
Example
3.4.
C++
3.4.1.
Output
3.4.2.
Explanation
3.5.
Reading a File
3.5.1.
Syntax
3.5.2.
Example
3.6.
C++
3.6.1.
Output
3.6.2.
Explanation
3.7.
Closing a File
3.7.1.
Syntax
3.7.2.
Example
3.8.
C++
3.8.1.
Explanation
4.
What is Synchronization?
5.
Frequently Asked Questions
5.1.
What is file handling in CPP?
5.2.
What are the benefits of file handling in C++?
5.3.
How to store data using file handling in C++?
5.4.
What is end of file handling in C++?
6.
Conclusion
Last Updated: Apr 18, 2024
Easy

File Handling in Cpp

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

File handling is used to store data on a computer permanently. With the help of file handling we can store our data in secondary memory. File handling in Cpp is a technique for storing a program's output in a file and performing various operations on it. Files aid in the permanent storing of data on a storage device.

file handling in cpp

In this article, we will learn how to open and close files, read data from files, write data to files, and modify files. We will also learn the various file access methods. We will also look at the many C++ functions available for carrying out these tasks. You will have a good understanding of file handling in cpp by the end of this article and be able to use files effectively.

What is File Handling in C++?

Files are used to store relevant data in a storage device. It is a method of storing the program output in a file and thus performing different operations on it. A stream is an abstraction that depicts a device that performs input and output actions. Depending on its application, a stream can be represented as the source or destination of various types of data, including characters, numbers, and objects.

File handling in CPP

We can use three different classes for file-handling methods in C++:- Ifstream, ofstream, and fstream. These classes are subclasses of fstreambase and the associated iostream class. These classes, designed to manage disc files, are declared in fstream, so we must include the fstream library in our program.

Data TypeDescription
fstreamAdd info about this
ifstreamAdd info about this
ofstreamAdd info about this

fstream Library

The library fstream is used for file handling in cpp. It allows us to read and write files in a program. It is a part of the standard library in C++. We will discuss the class we can use to perform I/O operations on files. In C++, files are dealt using three classes:

ifstream

The ifstream class is used to read data from files and signifies the input file stream.

ofstream

The ofstream class is used in creating and adding data to the file obtained from the program’s output. It is used for output operations and is also known as the output file stream.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

File operations in C++

File handling in cpp provides the following four operations:

  • open(): It is used to create a file and also used to open an existing file.
     
  • read(): It is used for reading data from a file.
     
  • write(): Used to write new data in a file.
     
  • close(): Used to close the file.
     

Now let’s discuss all these operations along with their example:

Opening a File

The open() operation is used to open a file to read or write data into it. We use the ‘ifstream’ library to read the file and ‘ofstream’ or ‘fstream’ library for writing in the file. Let’s look at its syntax:

Syntax

open( ‘File Name’, Mode)

File Name: It is the name of the desired file that the user will open.

Mode: There are various mode to open the file. Let’s look at each of them in the below table:

SyntaxModeDescription
ios::inReadIt opens the file to read.
ios::outWriteIt opens the file to write.
ios::binaryBinaryIt opens the file in binary mode.
ios::appAppendFile is opened in append mode.
ios::ateAt endOpen the file in append mode and move the read and write control at the end of the file.
ios::truncTruncate before openIt removes the data in the existing file.
ios::nocreateNo createIt opens the file only if it already exists.
ios::noreplaceNo replaceIt opens the file only if it does not already exists.

Example

Now, let’s look at the implementation of the open() method in C++:

  • C++

C++

#include<bits/stdc++.h>
#include <fstream>

using namespace std;

int main()
{
// Create a file stream object
fstream file;

// Opening file in write mode
file.open("welcome.txt",ios::out);

// If file does not open
if(!file)
{
cout<<"Failed to open file.\n";
return 1;
}

else
{
cout<<"File created using open() method";
}

// Closing file
file.close();

return 0;
}

Output

Output

Explanation

In the above program, we are creating a file named ‘Welcome.txt’ in write mode. After the successful execution of the program you can check a text file has been created in your system.

Writing a File

In this section, we will learn how to write data into a file that we created in the above section. The file we named is ‘Welcome.txt.’ We will use the stream insertion operator (<<) to write data into our file.

Syntax

File_Name<<"Insert your data";

Example

Now, let’s look at the implementation in C++:

  • C++

C++

#include<bits/stdc++.h>
#include <fstream>
using namespace std;

int main()
{
// Create a file stream object
fstream file;

// Opening file in write mode
file.open("welcome.txt",ios::out);

// If the file does not open
if(!file)
{
cout<<"Failed to open file.\n";
return 1;
}

else
{
// Writing data into file
file << "Welcome to CodingNinjas";

// Output for the program
cout<<"File created and your data has been entered into the file";
}

// Closing file
file.close();

return 0;
}

Output

Output

Explanation

Text file

In the above program, we entered our data in the file that we had already created named ‘Welcome.txt.’ After the successful execution of the program, you can check the text file containing the data - ‘Welcome to CodingNinjas’ when the user opens the Welcome.txt file.

Reading a File

Extracting stored data from a file is an important part of file handling in cpp. Reading data is essential because we cannot perform our task without any relevant information about the data. C++ provides features like data reading, and here we will use fstream and ifstream.

Content of the file Welcome.txt:

Welcome to CodingNinjas, this is an example of reading the file.

Syntax

FileName>>Variable;

Example

Now, let’s look at the implementation in C++:

  • C++

C++

#include<bits/stdc++.h>
#include <fstream>
using namespace std;

int main()
{
// create a file stream object
fstream file;

string line;

// Opening file in read mode
file.open("welcome.txt",ios::in);

// If file do not open
if(!file)
{
cout<<"No file found to open.\n";
return 1;
}

else
{
// Getting the string line from file
while(getline (file,line))
{
cout<<line<<endl;
}
}

// Closing file
file.close();

return 0;
}

Output

Output

Explanation

In the above program, we are reading data from the text file Welcome.txt. The text inside the file was Welcome to CodingNinjas, this is an example of reading the file. In the above output, we can see the content is extracted from the file Welcome.txt.

Closing a File

When our program task is done, closing the file is a good practice. It clears the memory allocated for the execution of our program. We use the close() function to close the file.

Syntax

File_Name.close();

Example

Now, let’s look at the implementation in C++:

  • C++

C++

#include<bits/stdc++.h>
#include <fstream>

using namespace std;

int main()
{
// Create a file stream object
fstream file;

// Opening file in write mode
file.open("welcome.txt",ios::out);

// If file do not open
if(!file)
{
cout<<"Failed to open file.\n";
return 1;
}

else
{
cout<<"File opened";
}

// Closing the file when the task is done
file.close();

return 0;
}

Explanation

In the above program, we opened our file Welcome.txt. When our task is done we closed our file using the ‘file.close()’ function. It is always a good practice to close the file explicitly to free up the allocated disk space for the file.

What is Synchronization?

A buffer is a temporary memory holding area that act as an intermediate between a file and a program or other I/0 device. When this buffer is flushed, the information in the buffer is written back to the physical medium i.e., the file is called synchronization.

The streams get buffered by default due to performance reasons in cpp. We might get a delay in the expected change in file during the write operation. We can use the flush() function or the std::flush manipulator to force all buffered writes to be pushed into the file.

To close the file, explicitly using manipulators use flush() and endl and explicitly using member function use sync().

To summarize buffering and synchronization, sync() is an input stream member that clears all unread characters from the buffer, whereas flush() is an output stream member that passes buffered output down to the kernel.

Frequently Asked Questions

What is file handling in CPP?

File handling in C++ involves reading from and writing to files. It uses classes like ifstream and ofstream to manipulate text and binary files, enabling data storage and retrieval.

What are the benefits of file handling in C++?

Benefits of file handling in C++:

  1. Data Persistence: Store data in files for long-term use.
  2. Data Sharing: Share data between programs.
  3. Configuration: Store configuration settings.
  4. Data Analysis: Process large datasets.

How to store data using file handling in C++?

Create an output file stream using the ofstream class in C++ to store data via file handling. Use the open() method to open a file, and then use the insertion operators (\\) to write data into the file. Lastly, use the close() method to end the file.

What is end of file handling in C++?

The process of identifying the end of input while reading from a file is known as end-of-file (EOF) handling in C++. To make sure all the data has been read from the file, it's usually done by checking for the failbit flag or using the eof() function.

Conclusion

 In this article, file handling in C++ is briefly covered. Along with learning how to open, read from, write data to, and close files, we also covered the fstream library. You can check out our other blogs to enhance your knowledge:

You can refer to our guided paths on the Coding Ninjas Studio platform. You can check our course to learn more about DSADBMSCompetitive Programming.

Previous article
Input/Output Streams
Next article
Variables
Live masterclass