1. 程式人生 > 其它 >C++ Primer 5th筆記(8)chapter8 類:IO庫-檔案流

C++ Primer 5th筆記(8)chapter8 類:IO庫-檔案流

技術標籤:c++ primer筆記

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 file
		if (input) {          // if the file is ok, ``process'' this file
			process(input);
		}
		else
			cerr << "couldn't open: sstream" ;
	}

sstream內容為:
morgan 2015552368 8625550123
drew 9735550130
lee 6095550132 2015550175 8005550000

結果:
在這裡插入圖片描述
【引用】

  1. 程式碼 https://github.com/thefistlei/cplusprimer/blob/main/cprimer/cprimer/ioTest.h