文件的输入与输出
IO庫類型和頭文件
1.iostream istream,ostream,iostream
2.fstream ?ifstram,ofstream,fstream
3.sstream istringstream,ostringstream,stringstream
IO對象無拷貝和復制
fstream fstrm;//創(chuàng)建一個未綁定的文件流
fstream fstrm(s);//創(chuàng)建一個fstream,并打開文件名為s的文件
fstream fstrm(s,mode);//以指定模式打開文件
fstrm.open(s);//打開名為s的文件綁定到fstrm上
fstrm.close();//關(guān)閉文件
fstrm.is_open();//返回一個booL值,指出文件是否打開
文件操作:
1 vector<string > lines; 2 ifstream in("new2.txt"); 3 string word; 4 while (in>>word) { 5 lines.push_back(word); 6 } 7 for (auto w : lines) { 8 cout << w <<endl; 9 } 10 in.close();//文件模式?
in,以讀方式打開 ,只能對ifstream或fstream對象設定in
out,以寫方式打開,只能對ofstream或fstream對象設定out,以out模式打開會丟失文件數(shù)據(jù)
app,每次操作前定位到文件末尾
ate,打開文件后定位到文件末尾
trunc,截斷文件,必須設定out后設定
binary;//以二進制方式進行IO
ofstream out("new2.txt", ofstream::out | ofstream::trunc);
為保留文件需要同時顯式的指定app模式
?
ofstream f("directory.txt", fstream::out);//沒有則創(chuàng)建char s[]= "zheng \nwang \nli \nzhou \n ";//斜杠可換行f.write(s,sizeof(s)-1);//寫數(shù)據(jù),第二個參數(shù)是字符串的大小 f.close();ifstream in1("directory.txt");try {if (in1) cout << "open file success!" << endl;else {throw runtime_error("Invalid Filename!");}}catch (runtime_error err) {cout << err.what() << "\nTry again ? Enter y or n" << endl;char c;cin >> c;if (!cin || c == 'n') {exit(0);}}string line,word1;vector<PersonInfo > people;while (getline(in1, line)) {PersonInfo info;istringstream record(line);record >>info.name;while (record >> word) {info.phones.push_back(word);}people.push_back(info);}//throw表達式表所遇到的無法處理的問題//try以關(guān)鍵子開始,以一個或多個catch語句結(jié)束,處理異常*/?
?
IO庫類型和頭文件//iostream istream,ostream,iostream//fstream ?ifstram,ofstream,fstream//sstream istringstream,ostringstream,stringstream//IO對象無拷貝和復制IO庫類型和頭文件//iostream istream,ostream,iostream//fstream ?ifstram,ofstream,fstream//sstream istringstream,ostringstream,stringstream//IO對象無拷貝和復制
轉(zhuǎn)載于:https://www.cnblogs.com/bingzzzZZZ/p/8434176.html
總結(jié)