1. 程式人生 > >C/C++讀寫文字檔案、二進位制檔案

C/C++讀寫文字檔案、二進位制檔案

//採用CPP模式讀取txt
void TextRead_CPPmode()
{
	fstream f;
	f.open("txt_out.txt",ios::in);	
	//檔案開啟方式選項:
	// ios::in    = 0x01, //供讀,檔案不存在則建立(ifstream預設的開啟方式)
	// ios::out    = 0x02, //供寫,檔案不存在則建立,若檔案已存在則清空原內容(ofstream預設的開啟方式)
	// ios::ate    = 0x04, //檔案開啟時,指標在檔案最後。可改變指標的位置,常和in、out聯合使用
	// ios::app    = 0x08, //供寫,檔案不存在則建立,若檔案已存在則在原檔案內容後寫入新的內容,指標位置總在最後
	// ios::trunc   = 0x10, //在讀寫前先將檔案長度截斷為0(預設)
	// ios::nocreate = 0x20, //檔案不存在時產生錯誤,常和in或app聯合使用
	// ios::noreplace = 0x40, //檔案存在時產生錯誤,常和out聯合使用
	// ios::binary  = 0x80  //二進位制格式檔案
	vector<int> index;
	vector<double> x_pos;
	vector<double> y_pos;
	if(!f)
	{
		cout << "開啟檔案出錯" << endl;
		return;
	}
	cout<<"mode為1,按字元讀入並輸出;mode為2,按行讀入輸出;mode為3,知道資料格式,按行讀入並輸出"<<endl;
	int mode = 1;
	cin>>mode;
	if(1== mode)
	{
		//按位元組讀入並輸出
		char ch;
		while(EOF != (ch= f.get()))
			cout << ch;
	}
	else if(2 == mode)
	{
		//按行讀取,並顯示
		char line[128];
		int numBytes;
		f.getline(line,128);
		cout << line << "\t" << endl ;
		f.getline(line,128);
		cout << line << "\t" << endl ;
		f.seekg(0,0);							//跳過位元組
		//seekg(絕對位置);      //絕對移動,    //輸入流操作
		//seekg(相對位置,參照位置);  //相對操作
		//tellg();					 //返回當前指標位置
		while(!f.eof())
		{
			//使用eof()函式檢測檔案是否讀結束
			f.getline(line,128);
			numBytes = f.gcount();		//使用gcount()獲得實際讀取的位元組數
			cout << line << "\t" << numBytes << "位元組" << endl ;
		}
	}
	else if(3 == mode)
	{
		//如果知道資料格式,可以直接用>>讀入
		int index_temp = 0;
		double x_pos_temp = 0, y_pos_temp = 0;
		while(!f.eof())
		{
			f >> index_temp >> x_pos_temp >> y_pos_temp ;
			index.push_back(index_temp);
			x_pos.push_back(x_pos_temp);
			y_pos.push_back(y_pos_temp);
			cout << index_temp << "\t" << x_pos_temp << "\t" << y_pos_temp << endl;
		}
	}
	f.close();
}