सी++ फ़ाइलें
सी++ फ़ाइलें
fstream
पुस्तकालय हमें फाइलों के साथ काम करने की अनुमति देता है ।
fstream
पुस्तकालय का उपयोग करने के लिए , मानक <iostream>
और<fstream>
शीर्षलेख फ़ाइल दोनों शामिल करें :
उदाहरण
#include <iostream>
#include <fstream>
पुस्तकालय में तीन वर्ग शामिल हैं fstream
, जिनका उपयोग फाइलें बनाने, लिखने या पढ़ने के लिए किया जाता है:
Class | Description |
---|---|
ofstream |
Creates and writes to files |
ifstream |
Reads from files |
fstream |
A combination of ofstream and ifstream: creates, reads, and writes to files |
फ़ाइल बनाएं और लिखें
फ़ाइल बनाने के लिए, या तो ofstream
या fstream
वर्ग का उपयोग करें, और फ़ाइल का नाम निर्दिष्ट करें।
फ़ाइल में लिखने के लिए, सम्मिलन ऑपरेटर ( <<
) का उपयोग करें।
उदाहरण
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
//
Write to the file
MyFile << "Files can be tricky, but it is fun
enough!";
//
Close the file
MyFile.close();
}
हम फाइल को बंद क्यों करते हैं?
इसे अच्छा अभ्यास माना जाता है, और यह अनावश्यक मेमोरी स्पेस को साफ कर सकता है।
एक फ़ाइल पढ़ें
किसी फ़ाइल से पढ़ने के लिए, ifstream
या तो fstream
कक्षा और फ़ाइल के नाम का उपयोग करें।
ध्यान दें कि हम फ़ाइल लाइन को लाइन से पढ़ने और फ़ाइल की सामग्री को प्रिंट करने के लिए फ़ंक्शन (जो कक्षा से संबंधित है ) while
के साथ एक लूप का भी उपयोग करते हैं:getline()
ifstream
उदाहरण
// Create a
text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while
loop together with the getline() function to read the file line by line
while (getline (MyReadFile,
myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();