Do you think IIT Guwahati certified course can help you in your career?
No
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.
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.
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.
C++ Streams for File Handling
C++ streams for file handling, such as ifstream, ofstream, and fstream, allow reading, writing, and modifying files efficiently. These classes from the <fstream> library provide functions to open, read, write, and close files.
Classes for File Stream in C++
We can use three different classes for file-handling methods in C++:
Ifstream
ofstream
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.
1. ifstream: ifstream is used to read data from files. It opens a file in read-only mode, allowing data to be extracted without modifying the file.
Example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inputFile("example.txt"); // Open file for reading
string line;
if (inputFile.is_open()) {
while (getline(inputFile, line)) { // Read line by line
cout << line << endl;
}
inputFile.close(); // Close the file after reading
} else {
cout << "Unable to open file for reading." << endl;
}
return 0;
}
Output: (Example.txt contains the text "Hello, World!")
Hello, World!
2. ofstream: ofstream is used to write data to files. It opens a file in write-only mode and can create a new file if it doesn’t exist or overwrite existing content.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outputFile("output.txt"); // Open file for writing
if (outputFile.is_open()) {
outputFile << "Writing to file with ofstream!" << endl; // Write text
outputFile.close(); // Close the file after writing
} else {
cout << "Unable to open file for writing." << endl;
}
return 0;
}
Output: (Content of output.txt)
Writing to file with ofstream!
3. fstream: fstream can be used for both reading and writing. It opens a file in read/write mode, allowing data to be modified and read within the same stream.
Example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
fstream file("data.txt", ios::in | ios::out | ios::trunc); // Open for reading/writing, truncate old content
if (file.is_open()) {
file << "Learning C++ file handling!" << endl; // Write to file
file.seekg(0); // Move the pointer back to the start of the file
string line;
while (getline(file, line)) { // Read and print file content
cout << line << endl;
}
file.close();
} else {
cout << "Unable to open file for reading and writing." << endl;
}
return 0;
}
Output: (Content of data.txt will be displayed on the console)
Learning C++ file handling!
File operations in C++
File handling in cpp provides the following four operations:
Operation
Description
Syntax Example
open()
Used to create a new file or open an existing file.
file.open("filename.txt");
read()
Reads data from a file.
file >> data; or getline(file, data);
write()
Writes new data into a file.
file << "Hello, World!";
close()
Closes the file after operations are complete.
file.close();
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.
Opening Modes
Mode: There are various mode to open the file. Let’s look at each of them in the below table:
Syntax
Mode
Description
ios::in
Read
It opens the file to read.
ios::out
Write
It opens the file to write.
ios::binary
Binary
It opens the file in binary mode.
ios::app
Append
File is opened in append mode.
ios::ate
At end
Open the file in append mode and move the read and write control at the end of the file.
ios::trunc
Truncate before open
It removes the data in the existing file.
ios::nocreate
No create
It opens the file only if it already exists.
ios::noreplace
No replace
It 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; }
You can also try this code with Online C++ Compiler
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; }
You can also try this code with Online C++ Compiler
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’ whenthe 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; }
You can also try this code with Online C++ Compiler
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; }
You can also try this code with Online C++ Compiler
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.
File Position Pointers
File position pointers manage where data is read from or written to within a file. In C, functions like fseek, ftell, and rewind control file position pointers.
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r+");
fseek(file, 5, SEEK_SET); // Move to the 5th position
fprintf(file, "Hello");
long position = ftell(file); // Get current position
printf("Current Position: %ld\n", position);
rewind(file); // Go back to the start
position = ftell(file);
printf("After Rewind, Position: %ld\n", position);
fclose(file);
return 0;
}
Output:
Current Position: 10
After Rewind, Position: 0
Checking State Flags
feof(FILE *stream): Checks for the end-of-file.
ferror(FILE *stream): Checks if an error has occurred.
clearerr(FILE *stream): Clears EOF and error flags.
Flushing a Stream
Stream flushing forces buffered data to be written to the disk immediately. Use fflush() to flush output buffer or fflush(NULL) to flush all output streams.
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.
Benefits of file handling in C++
Benefits of file handling in C++:
Data Persistence: Store data in files for long-term use.
Data Sharing: Share data between programs.
Configuration: Store configuration settings.
Data Analysis: Process large datasets.
Frequently Asked Questions
What is a file in C++?
In C++, a file is an external storage entity used to store data persistently. It can be read from or written to using file handling classes like ifstream, ofstream, and fstream within the <fstream> library.
What is the file name of a file in C++?
The file name in C++ is the path or identifier used to access a specific file. It is passed as a string argument to file stream objects (e.g., "data.txt") and defines where the file is stored or accessed.
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, we discussed file handling in C++. It is an essential skill for developers, enabling efficient data storage and retrieval. By mastering file streams, including reading, writing, and managing files, programmers can enhance their applications' functionality. Whether using text or binary files, understanding concepts like file pointers, state flags, and stream flushing allows for better control over data management.
You can check out our other blogs to enhance your knowledge: