Introduction
Programming में कई बार हमें data को permanently store करने की आवश्यकता होती है, ताकि program बंद होने के बाद भी data सुरक्षित रहे। इसके लिए files का उपयोग किया जाता है।
C++ में File Handling के माध्यम से हम files को create, read, write और modify कर सकते हैं। यह concept real-world applications जैसे database systems, logging systems और report generation में बहुत महत्वपूर्ण होता है।
Definition
File Handling वह प्रक्रिया है जिसके माध्यम से program external files (disk पर stored data) के साथ input और output operations perform करता है।
Header File
File handling के लिए C++ में <fstream> header file का उपयोग किया जाता है।
#include <fstream>
File Streams के प्रकार
1. ofstream (Output File Stream)
File में data लिखने (write) के लिए उपयोग होता है।
2. ifstream (Input File Stream)
File से data पढ़ने (read) के लिए उपयोग होता है।
3. fstream
File में read और write दोनों operations के लिए उपयोग होता है।
File Open करने का Syntax
fileObject.open("filename");
या
ofstream file("data.txt");
File में लिखना (Writing to File)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("data.txt");
file << "Hello File Handling";
file.close();
return 0;
}
Output:
File में "Hello File Handling" लिख दिया जाएगा
File से पढ़ना (Reading from File)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("data.txt");
string text;
file >> text;
cout << text;
file.close();
return 0;
}
Output:
Hello
Working को समझना
ofstream→ file में data लिखता हैifstream→ file से data पढ़ता हैopen()→ file खोलता हैclose()→ file बंद करता है
File Modes (संक्षेप में)
ios::in→ read modeios::out→ write modeios::app→ append modeios::binary→ binary mode
Example (Append Mode)
ofstream file("data.txt", ios::app);
Important Points
- File को use करने के बाद close करना जरूरी है
- File open न होने पर error check करना चाहिए
- Data permanently store होता है
- File modes का सही उपयोग आवश्यक है
Advantages
- Data permanent storage में रहता है
- Large data handle करना आसान होता है
- Data sharing संभव होता है
- Real-world applications में उपयोगी
निष्कर्ष
File Handling C++ में एक महत्वपूर्ण concept है जो data को external storage में manage करने की सुविधा देता है। यह program को अधिक practical और real-world उपयोग के लिए सक्षम बनाता है।