C++ ဖိုင်များ
C++ ဖိုင်များ
စာ 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
အတန်းအစားနှင့် ဖိုင်အမည်ကို အသုံးပြုပါ။
ဖိုင်ကိုမျဉ်းကြောင်းတစ်ခုစီဖတ်ရန်နှင့် ဖိုင်၏အကြောင်းအရာကို print ထုတ်ရန် (အတန်း နှင့်သက်ဆိုင်သော) function ( အတန်း while
နှင့်သက်ဆိုင်သော) loop တစ်ခုကိုလည်း အသုံးပြုကြောင်း သတိပြုပါ ။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();