C++ Primer 5th笔记(8)chapter8 类:IO库-文件流
1.創建一個文件流
ifstream in(ifile);//打開文件
ofstream out;//不打開文件
2. 文件輸入輸出類繼承自iostream類,可以使用iostream類的操作
fstream特有操作
fstream fstrm;// 創立一個未綁定的文件流
fstream fstrm(s);//創立一個fstream,并打開名為s的文件
fstream fstrm(s,mode); //與前一個函數類似,但按指定mode打開文件
fstrm.open(s) //打開名為s的文件,并將文件與fstrm綁定
fstrm.close()//關閉與fstrm綁定的文件
fstrm.is_open()// 返回一個bool值,指出與fstrm關聯的文件是否成功打開且尚未關閉
3. open 一個流對象打開一個文件
void open (const char *filename, openmode mode) ;
這里filename 是一個字符串,代表要打開的文件名,
mode 可以是標志符的組合:
ios::in 為輸入(讀)而打開文件,僅用做ifstream或fstream
ios::out 為輸出(寫)而打開文件,僅用做ofstream或fstream
ios::ate //打開就尋找末尾
ios::app 所有輸出附加在文件末尾
ios::trunc 如果文件已存在則先刪除該文件
ios::binary 二進制方式來操作文件
eg.
ofstream file ; file.open ("example.bin", ios::out | ios::app | ios::binary) ;ofstream file("example.bin", ios::out | ios::app | ios::binary);<=> ofstream file ; file.open("example.bin",ios::out | ios::app | ios::binary) ;- 必須先關閉已經關聯的文件,才可以打開新的文件。 當一個fstream對象被銷毀時,close會自動被調用。
- 默認情況下,即使不設置trunc,以out模式打開的文件也會被截斷,文件原有的內容被清空。
- 保留被ofstream打開的文件中已有數據的唯一方法是顯式地指定app或者in模式。
- 不能對輸入流設置out模式,也不能對輸出流設置in模式。
eg.
void static process(ifstream& is){string s;while (is >> s)cout << s << endl;}void static ioFile(){ifstream input("sstream"); // create input and open the fileif (input) { // if the file is ok, ``process'' this fileprocess(input);}elsecerr << "couldn't open: sstream" ;}sstream內容為:
morgan 2015552368 8625550123
drew 9735550130
lee 6095550132 2015550175 8005550000
結果:
【引用】
總結
以上是生活随笔為你收集整理的C++ Primer 5th笔记(8)chapter8 类:IO库-文件流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ Primer 5th笔记(8)c
- 下一篇: C++ Primer 5th笔记(8)c