Introduction to File Handling
In C++ programming, file handling is a crucial concept that allows programs to store, retrieve, and manipulate data in external files instead of just using console input and output. By using files, we can create persistent storage, meaning data remains available even after the program terminates.
File handling in C++ is done using the fstream library, which provides classes to perform various operations such as reading, writing, appending, and modifying files. This enables efficient data management, especially in applications dealing with large amounts of data.
Why is File Handling Important?
✅ Data Persistence – Data remains even after program execution ends.
✅ Efficient Data Storage – Instead of storing data in RAM, files store data on disk, saving memory.
✅ Data Sharing & Transfer – Data can be shared across different programs or systems.
✅ Backup & Logging – Used in applications that require maintaining records, such as logs.
✅ Handling Large Data Sets – Useful when working with databases, large text files, and reports.
Types of File Handling in C++
C++ supports two types of file handling based on data format:
1. Text Files
Stores data in a human-readable format.
Data is saved as characters.
Example: .txt, .csv, .log files.
Used for storing readable data, such as logs, configurations, and reports.
2. Binary Files
Stores data in a non-human-readable format (0s and 1s).
Faster than text files because there is no conversion of characters.
Example: .dat, .bin files.
Used for storing structured data, such as images, executable files, and databases.
File Handling Operations in C++
C++ provides various file operations using the <fstream> library, which contains three main classes:
1. ofstream (Output File Stream)
Used to write data to a file.
Creates a file if it doesn’t exist.
Syntax:
cpp
Copy
Edit
#include <fstream>
ofstream file("example.txt");
file << "Hello, World!";
file.close();
2. ifstream (Input File Stream)
Used to read data from a file.
Syntax:
cpp
Copy
Edit
#include <fstream>
ifstream file("example.txt");
string text;
file >> text;
file.close();
3. fstream (File Stream - Read/Write Mode)
Can both read and write to a file.
Syntax:
cpp
Copy
Edit
#include <fstream>
fstream file("example.txt", ios::in | ios::out);
File Opening Modes in C++
When working with files, we need to specify the mode in which we want to open them. These modes are provided by ios (input-output stream) in C++.
Mode Description
ios::in Opens file for reading.
ios::out Opens file for writing (overwrites if exists).
ios::app Opens file for appending (adds data at the end).
ios::ate Opens file and moves the pointer to the end.
ios::binary Opens file in binary mode.
Example:
cpp
Copy
Edit
fstream file("example.txt", ios::in | ios::out | ios::app);
Writing to a File in C++ (Text Mode)
To write data to a file, we use ofstream or fstream with ios::out.
Example:
cpp
Copy
Edit
#include <iostream>
#include <fstream>
using names