本文共 2564 字,大约阅读时间需要 8 分钟。
??????????????????????????????????????????????????????????????????C++????????????? <fstream>?
???????????
????????????
?????????
#include <fstream>?ofstream ofs;?ofs.open("????", ????);?ofs << "?????";?ofs.close();????????????????????????
| ???? | ?? |
|---|---|
ios::in | ????? |
ios::out | ????? |
ios::ate | ????????? |
ios::app | ??????? |
ios::trunc | ????????????????? |
ios::binary | ??????????? |
???
#include#include void test01() { ofstream ofs("test.txt", ios::out); ofs << "?????" << endl; ofs << "????" << endl; ofs << "???18" << endl; ofs.close();}int main() { test01(); system("pause"); return 0;}
?????????
#include <fstream>?ifstream ifs;?ifs.open("????", ????);?ifs.close();????
#include#include void test01() { ifstream ifs("test.txt", ios::in); if (!ifs.is_open()) { cout << "??????" << endl; return; } // ???????????? char buf[1024] = {0}; while (ifs >> buf) { cout << buf << endl; } // ???? char buf[1024] = {0}; while (ifs.getline(buf, sizeof(buf))) { cout << buf << endl; } // ????????? string buf; while (getline(ifs, buf)) { cout << buf << endl; } char c; while ((c = ifs.get()) != EOF) { cout << c; } ifs.close();}int main() { test01(); system("pause"); return 0;}
??????????????????write???????????
ostream& write(const char* buffer, int len);
???
#include#include struct Person { char m_Name[64]; int m_Age;};void test01() { ofstream ofs("person.txt", ios::out | ios::binary); Person p = {"??", 18}; ofs.write((const char*)&p, sizeof(p)); ofs.close();}int main() { test01(); system("pause"); return 0;}
??????????????????read???????????
istream& read(char* buffer, int len);
???
#include#include struct Person { char m_Name[64]; int m_Age;};void test01() { ifstream ifs("person.txt", ios::in | ios::binary); if (!ifs.is_open()) { cout << "??????" << endl; return; } Person p; ifs.read((char*)&p, sizeof(p)); cout << "??? " << p.m_Name << " ??? " << p.m_Age << endl; ifs.close();}int main() { test01(); system("pause"); return 0;}
?????????????????????????????????
转载地址:http://bke.baihongyu.com/