C++ IO学习
關于IO,主要有這么三種類型:標準輸入輸出,文件輸入輸出,字符串流。后面兩種都是繼承自第一種標準輸入輸出的。他們分別對應的頭文件是:
標準輸入輸出:#include <iostream>
文件輸入輸出:#include <fstream>
字符串流:#include <sstream>
流對象是不能復制和拷貝的。因此流對象不能用于賦值和參數傳遞,如果一定要傳遞,那么必須傳遞指針或者引用。
這里記錄了一個例子來說明,流對象的使用,通過這個使用,來說明流對象的屬性狀態。上代碼,假如在本地D盤根目錄下有個文件hello.txt。文件中的內容是001--006。
1 #include "stdafx.h" 2 #include <fstream> 3 #include <sstream> 4 #include <iostream> 5 6 using namespace std; 7 8 9 ifstream &print(ifstream &in) 10 { 11 string str; 12 13 cout << in.bad() << endl; 14 cout << in.good() << endl; 15 cout << in.fail() << endl; 16 cout << in.eof() << endl; 17 cout << "--------------------1" << endl; 18 while (in >> str) 19 { 20 cout << str << endl; 21 } 22 cout << "--------------------2" << endl; 23 cout << in.bad() << endl; 24 cout << in.good() << endl; 25 cout << in.fail() << endl; 26 cout << in.eof() << endl; 27 cout << "--------------------3" << endl; 28 in.clear(); 29 cout << in.bad() << endl; 30 cout << in.good() << endl; 31 cout << in.fail() << endl; 32 cout << in.eof() << endl; 33 in.seekg(0, ios_base::beg); 34 return in; 35 } 36 37 int main() 38 { 39 ifstream in("d://hello.txt"); 40 string str; 41 print(in); 42 while (in >> str) 43 { 44 cout << str << endl; 45 } 46 in.close(); 47 return 0; 48 }?
如上代碼示例了讀取一個文件,并將文件內容打印到控制臺上,并且將IO流重置,并且重新打印一遍。?
其中如下代碼表示了流對象的四種狀態:
in.bad() 如果流被破壞,則返回true. in.good()如果流處于有效狀態,則返回true。 in.fail() 如果IO操作失敗,則返回true。 in.eof() 如果讀取文件到了文件末尾,則返回true。 in.clear(); 用于重置所有的狀態。in.seekg(0, ios_base::beg); 將文件操作的指針重置到文件開始處。
?
轉載于:https://www.cnblogs.com/lucy-lizhi/p/6506261.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
- 上一篇: Discuz常见小问题-_如何修改网站L
- 下一篇: 会汽车机修给别人打工能赚多少钱一个月?