1.
Introduction to File Handling
What is File Handling?
File handling in C++ allows us to store and retrieve data from files permanently. Instead of
relying on user input every time, we can store and read data from a file.
Why Use File Handling?
• Data Persistence: Stores data beyond program execution.
• Efficient Data Management: Handles large datasets.
• Inter-Process Communication: Data sharing between different programs.
2. File Streams in C++
C++ provides the <fstream> library to work with files. The main file handling classes are:
Stream Class Description
ifstream Input file stream (reading from a file)
ofstream Output file stream (writing to a file)
fstream General file stream (both reading and writing)
To use file handling in C++, include the <fstream> library.
#include <iostream>
#include <fstream>
using namespace std;
3. Opening and Closing Files
Before working with files, we need to open and close them properly.
Opening a File
We use the .open() function to open a file.
ofstream outFile;
outFile.open("example.txt"); // Opens a file for writing
Closing a File
Always close a file after use to free system resources.
outFile.close(); // Closes the file
Alternatively, we can use file objects directly:
ofstream outFile("example.txt"); // Opens file
outFile << "Hello, File Handling!"; // Writes data
outFile.close(); // Closes file
4. Writing Data to a File
To write data into a file, we use the ofstream class.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("data.txt"); // Open file for writing
if (outFile.is_open()) {
outFile << "John 25" << endl;
outFile << "Alice 30" << endl;
outFile.close();
cout << "Data written to file successfully." << endl;
} else {
cout << "Error opening file!" << endl;
}
return 0;
}
Explanation:
• The program creates and opens data.txt.
• It writes two lines of formatted text.
• It ensures the file is closed properly.
5. Reading Data from a File
To read data, we use the ifstream class.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream inFile("data.txt"); // Open file for reading
string name;
int age;
if (inFile.is_open()) {
while (inFile >> name >> age) {
cout << "Name: " << name << ", Age: " << age << endl;
}
inFile.close();
} else {
cout << "Error opening file!" << endl;
}
return 0;
}
Explanation:
• The program opens data.txt for reading.
• It reads and displays each line.
6. File Modes in C++
Mode Description
ios::in Opens file for reading
ios::out Opens file for writing (overwrites existing data)
ios::app Opens file in append mode (adds data at the end)
ios::ate Opens file at the end
ios::trunc Truncates file if it exists
Example: Using ios::app Mode
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("data.txt", ios::app); // Append mode
if (outFile.is_open()) {
outFile << "New Data Entry" << endl;
outFile.close();
cout << "Data appended successfully." << endl;
} else {
cout << "Error opening file!" << endl;
}
return 0;
}
Key Difference: Unlike ios::out, the ios::app mode adds new data instead of
overwriting.
7. Writing and Reading Formatted Data
C++ supports both formatted (structured) and unformatted (raw) file handling.
Formatted Writing
#include <fstream>
using namespace std;
int main() {
ofstream outFile("formatted.txt");
int id = 101;
double price = 99.99;
outFile << "ID: " << id << ", Price: $" << price << endl;
outFile.close();
return 0;
}
Formatted Reading
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream inFile("formatted.txt");
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
return 0;
}
8. Problem-Solving Examples
Example 1: Writing Student Records to a File
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("students.txt");
string name;
int age;
for (int i = 0; i < 3; i++) {
cout << "Enter name: ";
cin >> name;
cout << "Enter age: ";
cin >> age;
outFile << name << " " << age << endl;
}
outFile.close();
return 0;
}
Explanation:
• The program takes 3 student records and writes them to students.txt.
Example 2: Reading Student Records from a File
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream inFile("students.txt");
string name;
int age;
while (inFile >> name >> age) {
cout << "Name: " << name << ", Age: " << age << endl;
}
inFile.close();
return 0;
}
Explanation:
• The program reads and displays student records from students.txt.
9. Best Practices in File Handling
✅ Always check if a file is open before reading/writing.
✅ Close files after operations to free system resources.
✅ Use ios::app mode to prevent overwriting.
✅ Handle file errors properly using conditions.
10. Summary
• File Handling is essential for persistent data storage.
• File Streams: ifstream, ofstream, and fstream.
• Modes: ios::in, ios::out, ios::app, etc.
• Formatted & Unformatted file operations.
• Problem-Solving: Writing and reading structured data.