c++中IO輸入輸出流總結<二>
1 文件的打開和關閉
1.1 定義流對象
ifsteam iflie;//文件輸入流對象
ifsteam iflie;//文件輸出流對象
fsteam iflie;//文件輸入輸出流對象
1.2 打開文件
void open(const unsigned char* filename,int mode,int accessfilebuf:opnprot)
mode為打開的方式,相關標記如下圖所示(ios中)
註意:
(1)通常打開方式用|組合起來
ios::in|ios::out //讀寫方式打開文件
ios::out|ios::binary //二進制寫方式打開文件
(2)iftream:默認ios::in
ofstream:默認ios::out|ios::trunc
fstream:默認ios::in|ios::out|ios::app
2 狀態函數
eof():讀文件到達末尾 true
bad():讀文件出錯返回true 當我打開一個不可以寫但是進行寫入的時候
fail:當需要輸入整形的時候我們輸入了字母
good:如果上面任何一個函數都是true的話 返回false
clear():
#include <iostream> #include <stdlib.h> using namespacestd; int main() { int integerV; cout << "before a bad input operation:" << "\n cin.eof():" << cin.eof() << "\n cin.fail():" << cin.fail() << "\ncin.bad():" << cin.bad() << "\ncin.good()" << cin.good() << endl; cin>> integerV;//control +D/Z cout << "after a bad input operation:" << "\n cin.eof():" << cin.eof() << "\n cin.fail():" << cin.fail() << "\ncin.bad():" << cin.bad() << "\ncin.good()" << cin.good() << endl; system("pause"); return 1; }
3 (cin)和(!cin)的分析
不管是while(cin)還是if(cin)都是合法的為什麽?自定義一個類,然後定義這個類的對象,使用if語句判斷它是不合法的。說明流對象有莫中轉換函數 可以將一個流對象轉換成判斷語句可以識別的類型
operator void*() const函數在while(cin)或者if(cin)隱式轉換位void*類型
bool operator!() const;函數在while(!cin)或者式if(!cin)被調用 將流對象轉換成bool對象
while(cin)--->while(!cin.fail)
while(!cin)---->while(cin.fail)
1 class A 2 { 3 public: 4 A(){} 5 ~A(){} 6 operator void*() const 7 { 8 cout << "cast to void*"; 9 return (void*)this; 10 } 11 bool operator!() const 12 { 13 cout << "cast to bool"; 14 return true; 15 } 16 }; 17 18 int main() 19 { 20 A a; 21 if (a)cout << "first" << endl; 22 if (!a)cout << "second" << endl; 23 system("pause"); 24 return 1; 25 }
4 文件讀寫操作
c++中IO輸入輸出流總結<二>