fstream बहुत अच्छे हैं लेकिन मैं थोड़ा गहराई से जाऊंगा और आपको RAII के बारे में बताऊंगा।
क्लासिक उदाहरण के साथ समस्या यह है कि आपको फ़ाइल को अपने आप बंद करने के लिए मजबूर होना पड़ता है, जिसका अर्थ है कि आपको इस आवश्यकता के लिए अपने आर्किटेक्चर को मोड़ना होगा। आरएआईआई आपके लिए फाइल बंद करने के लिए सी ++ में स्वचालित विनाशक कॉल का उपयोग करता है।
अद्यतन: ऐसा लगता है कि std :: fstream पहले ही आरएआईआई लागू करता है, इसलिए नीचे दिया गया कोड बेकार है। मैं इसे यहां पोस्टरिटी के लिए और आरएआईआई के उदाहरण के रूप में रखूंगा।
class FileOpener
{
public:
FileOpener(std::fstream& file, const char* fileName): m_file(file)
{
m_file.open(fileName);
}
~FileOpeneer()
{
file.close();
}
private:
std::fstream& m_file;
};
अब आप इस तरह अपने कोड में इस वर्ग का उपयोग कर सकते हैं:
int nsize = 10;
char *somedata;
ifstream myfile;
FileOpener opener(myfile, "<path to file>");
myfile.read(somedata,nsize);
// myfile is closed automatically when opener destructor is called
सीखना कैसे आरए II काम करता है आप कुछ सिर दर्द और कुछ प्रमुख स्मृति प्रबंधन कीड़े बचा सकता है।खोलने के लिए और एक बाइनरी फ़ाइल आप स्पष्ट रूप से अपने इनपुट धारा में पढ़ने प्रारूप की घोषणा करने की जरूरत है पढ़ने के लिए
// define your file name
string file_name = "data.txt";
// attach an input stream to the wanted file
ifstream input_stream(file_name);
// check stream status
if (!input_stream) cerr << "Can't open input file!";
// file contents
vector<string> text;
// one line
string line;
// extract all the text from the input file
while (getline(input_stream, line)) {
// store each line in the vector
text.push_back(line);
}
:
स्रोत
2008-08-11 16:07:31
[सी ++: फाइलों के साथ इनपुट/आउटपुट] (http://www.cplusplus.com/doc/tutorial/files.html) – mreggen
आरएआईआई में दिलचस्पी रखने वाले किसी भी व्यक्ति को जांचना चाहिए [आधिकारिक संसाधन प्रबंधन पेज] (http://www.relisoft.com/resource/resmain.html) Bartosz Milewski द्वारा। – titanae