1. 程式人生 > >文件的輸入與輸出

文件的輸入與輸出

string class 輸入 success 每次 time 處理異常 eof one

IO庫類型和頭文件

1.iostream istream,ostream,iostream

2.fstream ifstram,ofstream,fstream

3.sstream istringstream,ostringstream,stringstream

IO對象無拷貝和復制

fstream fstrm;//創建一個未綁定的文件流

fstream fstrm(s);//創建一個fstream,並打開文件名為s的文件

fstream fstrm(s,mode);//以指定模式打開文件

fstrm.open(s);//打開名為s的文件綁定到fstrm上

fstrm.close();//關閉文件

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模式打開會丟失文件數據

app,每次操作前定位到文件末尾

ate,打開文件後定位到文件末尾

trunc,截斷文件,必須設定out後設定

binary;//以二進制方式進行IO

ofstream out("new2.txt", ofstream::out | ofstream::trunc);

為保留文件需要同時顯式的指定app模式

ofstream f("directory.txt", fstream::out);//沒有則創建
    char s[]= "zheng \nwang \nli \nzhou \n ";//斜杠可換行
    f.write(s,sizeof(s)-1);//寫數據,第二個參數是字符串的大小
    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以關鍵子開始,以一個或多個catch語句結束,處理異常*/

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對象無拷貝和復制

文件的輸入與輸出