Programming mein jab hum apna data kisi file mein store karna chahte hain ya file se read karna chahte hain, tab use hota hai File Handling. C++ hume ifstream
, ofstream
, aur fstream
jaise classes deta hai jo file operations ko easy bana dete hain.
In this blog we'll learn about:
- File read & write karna
- File modes kya hote hain
- Text aur Binary files ka difference
1. File Handling ke liye konsi header file?
#include <fstream> // File handling ke liye
#include <iostream>
using namespace std;
2. File Write karna using ofstream
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream file("example.txt"); // file create ya open karega
if (file.is_open()) {
file << "Hello Duniya!\n";
file << "File Handling is easy.\n";
file.close(); // file close karna zaruri hai
cout << "File written successfully.\n";
} else {
cout << "File open nahi hui.\n";
}
return 0;
}
ofstream
is used for writing into files.
3. File Read karna using ifstream
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ifstream file("example.txt"); // file read mode mein open
string line;
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
} else {
cout << "File read nahi ho payi.\n";
}
return 0;
}
getline()
ek line puri read karta hai jab tak newline ('\n') na mile.
4. File Modes in C++
File open karte time hume specify karna padta hai ki kaunsa mode chahiye. Kuch common file modes:
ios::in
: File read mode
ios::out
: File write mode
ios::app
: Append at end
ios::ate
: Move pointer to end immediately after opening
ios::trunc
: Delete old content if file exists
ios::binary
: Binary file mode
Example:
ofstream file("data.txt", ios::app); // existing file ke end mein write karega
🔹 5. File Pointers in C++
C++ mein 2 important file pointers hote hain:
PointerPurposeget
Reading positionput
Writing position
Hum seekg()
aur seekp()
ka use karke file mein specific position par jump kar sakte hain.
Example:
ifstream file("data.txt");
file.seekg(0, ios::end); // pointer ko end par le jao
int size = file.tellg(); // file ka size return karega
cout << "File size: " << size << " bytes\n";
file.close();
6. Binary vs Text File
FeatureText FileBinary FileHuman readableHaan (Yes)Nahi (No)SizeZyadaKamExample.txt, .csv.exe, .dat, .binRead/WriteLine by lineByte by byte
Binary file write & read:
#include <fstream>
using namespace std;
int main() {
int num = 25;
// Write binary
ofstream out("binary.bin", ios::binary);
out.write((char*)&num, sizeof(num));
out.close();
// Read binary
int readNum;
ifstream in("binary.bin", ios::binary);
in.read((char*)&readNum, sizeof(readNum));
in.close();
cout << "Read from binary: " << readNum << endl;
return 0;
}
Comments