Chapter 11C++ Tutorial~1 min read
File Handling in C++
Files — Read/Write करणे
C++ मध्ये file handling साठी fstream header वापरतात. ofstream — write, ifstream — read, fstream — both. C च्या fopen/fclose पेक्षा more object-oriented approach.
File Write करणे — ofstream
Write to file
cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// ofstream — output file stream
ofstream outFile("notes.txt");
// File उघडली का? check करा
if (!outFile.is_open()) {
cout << "File उघडता आली नाही!" << endl;
return 1;
}
// File मध्ये लिहिणे — cout सारखेच!
outFile << "नमस्कार!" << endl;
outFile << "हे C++ File Handling चे notes आहेत." << endl;
outFile << "आज STL शिकलो." << endl;
outFile.close(); // File बंद करणे
cout << "File successfully लिहिली! ✅" << endl;
// Append mode — शेवटी add करणे
ofstream appendFile("notes.txt", ios::app);
appendFile << "Extra line appended." << endl;
appendFile.close();
return 0;
}File Read करणे — ifstream
Read from file
cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inFile("notes.txt");
if (!inFile.is_open()) {
cout << "File सापडली नाही!" << endl;
return 1;
}
// Line by line वाचणे
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
// Word by word वाचणे
ifstream f2("data.txt");
string word;
while (f2 >> word) {
cout << word << " ";
}
f2.close();
return 0;
}fstream — Read + Write दोन्ही
Student data save/load
cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Student {
string name;
int marks;
};
int main() {
// Write students
ofstream fw("students.txt");
Student students[] = {{"Rahul", 85}, {"Priya", 92}, {"Amit", 78}};
for (auto &s : students) {
fw << s.name << " " << s.marks << endl;
}
fw.close();
// Read back
ifstream fr("students.txt");
string name;
int marks;
cout << "Students:" << endl;
while (fr >> name >> marks) {
cout << " " << name << ": " << marks
<< (marks >= 40 ? " Pass ✅" : " Fail ❌") << endl;
}
fr.close();
return 0;
}💡
C++ file streams automatically close होतात जेव्हा object scope च्या बाहेर जातो (RAII). तरीही explicitly close() call करणे good practice आहे — data flush होतो.
✅ Key Points — लक्षात ठेवा
- ▸ofstream — write (creates/overwrites)
- ▸ifstream — read
- ▸fstream — read + write दोन्ही
- ▸ios::app — append mode
- ▸getline(file, str) — full line read
0/11 chapters पूर्ण