File Handling
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.
#include <iostream>
#include <fstream>
using namespace std;
Opening a File
ofstream outFile;
outFile.open("example.txt"); // Opens a file for writing
Closing a File
#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:
#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:
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.
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;
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;
Explanation:
int main() {
ifstream inFile("students.txt");
string name;
int age;
Explanation:
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.