C++ file handling is the process of reading and writing data to and from files. It is a fundamental part of C++ programming, and it is used in a wide variety of applications, such as web development, database programming, and scientific computing.
To perform file handling in C++, you use the following classes:
To open a file, you use the open() method. The open() method takes two parameters: the name of the file and the mode in which you want to open the file. The mode can be one of the following:
Once you have opened a file, you can read and write data to the file using the read() and write() methods, respectively.
The following code shows how to open a file for reading and write data to the file:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("input.txt");
ofstream fout("output.txt");
if (!fin.is_open()) {
cout << "Error opening input file." << endl;
return 1;
}
if (!fout.is_open()) {
cout << "Error opening output file." << endl;
return 1;
}
// Read data from the input file and write it to the output file.
string line;
while (getline(fin, line)) {
fout << line << endl;
}
fin.close();
fout.close();
return 0;
}
The following code shows how to append data to a file:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream fout("output.txt", ios::app);
if (!fout.is_open()) {
cout << "Error opening output file." << endl;
return 1;
}
fout << "This is the appended text." << endl;
fout.close();
return 0;
}
Once you have finished reading or writing to a file, you must close the file using the close() method.
Benefits of using file handling
There are several benefits to using file handling in C++, including:
Conclusion
File handling is a powerful feature of C++ that can be used to write a wide variety of applications. By understanding how to use file handling, you can write more robust and reliable code.
Please support us by disabling your ad blocker for this website.
We rely on advertising revenue to keep the lights on and content free.
Thank you for understanding ❤️