Importance of File Handling in C++ & How To Do It [2024]
Updated on Dec 20, 2023 | 9 min read | 9.2k views
Share:
For working professionals
For fresh graduates
More
Updated on Dec 20, 2023 | 9 min read | 9.2k views
Share:
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 –
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.
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 –
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++ –
Must Read: Top 8 Project Ideas in C++
Let’s discuss them thoroughly to understand how file handling in C++ works –
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 –
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 –
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 );
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();
}
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();
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?
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:
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
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
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.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources