File Handling in C++
File handling allows programs to store data permanently in files. Unlike variables, file data is not lost when the program ends. C++ provides built-in classes to create, read, write, and update files efficiently.
Why File Handling is Important
- Permanent data storage
- Data sharing between programs
- Data backup and recovery
- Handling large data sets
Header File for File Handling
#include <fstream>
This header file provides file-handling classes.
File Handling Classes in C++
C++ provides three main classes:
- ofstream – for writing to files
- ifstream – for reading from files
- fstream – for both reading and writing
Creating and Writing to a File
ofstream file("data.txt");
file << "Welcome to File Handling";
file.close();
Reading from a File
ifstream file("data.txt");
string data;
file >> data;
file.close();
File Open Modes
| Mode | Description |
|---|---|
| ios::in | Read mode |
| ios::out | Write mode |
| ios::app | Append mode |
| ios::binary | Binary mode |
| ios::trunc | Clear file content |
Appending Data to a File
ofstream file("data.txt", ios::app);
file << "New Data";
file.close();
Reading Line by Line
string line;
while(getline(file, line)) {
cout << line;
}
Checking File Errors
- Check if file opened successfully
- Handle missing or corrupted files
if(!file) {
cout << "File not found";
}
Binary File Handling
Used for storing objects and multimedia data.
file.write((char*)&obj, sizeof(obj));
Real-World Applications
- Student record systems
- Banking applications
- Log file management
- Data storage systems
- Report generation
Common Mistakes to Avoid
- Not closing files
- Incorrect file modes
- File path errors
- Ignoring error handling
Advantages of File Handling
- Data persistence
- Efficient data management
- Large data storage
- Improved application functionality
Conclusion
File handling in C++ enables permanent data storage using files. By using file streams and modes properly, programmers can efficiently read, write, and manage data. This concept is essential for building real-world, data-driven applications.