1. 程式人生 > >C++利用fstream讀寫檔案

C++利用fstream讀寫檔案

/*
C++的ifstream和ofstream
讀檔案寫檔案操作
*/
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
	//檔名
	string filename = "map_file.txt";
	//如果檔名是string型別的呼叫c_str成員獲取C風格字串
	//因為IO標準庫是使用C風格字串來作為檔名的
	//此處開啟檔案也可以用ifstream的成員函式open來執行
	ifstream infile(filename.c_str());
	//檢查檔案是否開啟成功
	if(!infile)
	{//如果沒成功

		throw runtime_error("file cannot open");
		return -1;
	}
	else
	{//檔案開啟成功,開始進行讀檔案操作
		string s;
		//fstream類中也有getline成員函式,不要弄錯
		//getline(infile,s);
		while(!infile.eof())
		{
			//infile >> s;
			getline(infile,s);
		    cout << s << endl;
		}
	}
	infile.close();
	//開啟檔案的時候可以用初始化
	//ofstream outfile(filename.c_str(),ofstream::out | ofstream::app);
	//也可以用ofstream的成員函式outfile.open(filename.c_str(),ofstream::out | ofstream::app)來進行開啟檔案
	//如果寫檔案的模式直接是out,則會清除原來檔案的內容,app模式是讓檔案指標定位到檔案尾再開始寫入
	ofstream outfile;
	outfile.open(filename.c_str(),ofstream::out | ofstream::app);
	if(!outfile)
	{//未成功開啟檔案
		throw runtime_error("file cannot open");
		return -1;
	}
	else
	{
		//在檔案map_file.txt檔案尾部進行寫入
		//有時,此處測試已經換行,檔案尾部沒有換行,在此需要換行寫入
		//outfile << endl;
		//在檔案中寫入 111    222資料
		outfile << "111   222" << endl;
		//檔案流一定要記著關閉
		outfile.close();
	}
	return 0;
}