Q9. Demonstrate File Handling in C++
Question:
Write a program to demonstrate file handling.
My Approach
File handling ka matlab hota hai ki program directly file se data read aur write kar sake.
C++ me iske liye teen important classes hoti hain (header <fstream> ke andar):
ofstream→ File me likhne (Write) ke liye.ifstream→ File se padne (Read) ke liye.fstream→ File ko dono tarah (read + write) ke liye.
Program Code
File Name: file_handling_demo.cpp
#include <iostream>
#include <fstream>
using namespace std;
int main() {
string name;
int rollNo;
float marks;
// File me data likhna
ofstream outFile("student.txt"); // file create/open
if (!outFile) {
cout << "File could not be opened for writing!" << endl;
return 1;
}
cout << "Enter Student Name: ";
getline(cin, name);
cout << "Enter Roll No: ";
cin >> rollNo;
cout << "Enter Marks: ";
cin >> marks;
outFile << "Name: " << name << endl;
outFile << "Roll No: " << rollNo << endl;
outFile << "Marks: " << marks << endl;
outFile.close(); // file band karna zaroori hai
cout << "\nData successfully written to student.txt\n" << endl;
// File se data read karna
ifstream inFile("student.txt");
if (!inFile) {
cout << "File could not be opened for reading!" << endl;
return 1;
}
cout << "=== Reading Data from File ===" << endl;
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
return 0;
}Sample Output
Enter Student Name: Intesab Ansari
Enter Roll No: 101
Enter Marks: 89.5
Data successfully written to student.txt
=== Reading Data from File ===
Name: Intesab Ansari
Roll No: 101
Marks: 89.5Explanation
ofstream outFile("student.txt");→ File create hoti hai aur usme data write hota hai.ifstream inFile("student.txt");→ Same file se data read hota hai.getline(inFile, line)→ File ko line by line read karta hai.close()function ka use karna zaroori hota hai memory aur resources free karne ke liye.
Real-Life Scenario
- Example: Jab tumhare college ke students ka data maintain karna ho:
- Name, Roll No, Marks ko ek file me store karna.
- Later wo file se read karke result generate karna.
Yehi kaam hamne program me kiya hai.
Conclusion
- File handling C++ me input/output ko persistent storage (files) ke saath connect karta hai.
ofstream,ifstream, aurfstreamka use karke data read aur write karna easy ho jata hai.
Submitted by:
Intesab Ansari
MCA Student, NMU University
Portfolio: intesab.live
Last updated on