1. 程式人生 > >C++:替換檔案中的指定字串

C++:替換檔案中的指定字串

替換文字檔案或者二進位制檔案中的指定字串

// 方法一
// 將原始檔中的特定字串替換,內容輸出到新檔案中
bool FileStringReplace(ifstream &instream, ofstream &outstream)
{
	string str;
	size_t pos = 0;
	while (getline(instream, str)) // 按行讀取
	{
		pos = str.find("Tom"); // 查詢每一行中的"Tom"
		if (pos != string::npos)
		{
			str = str.replace(pos, 9, "Lucy")
; // 將Tom替換為Lucy outstream << str << endl; continue; } outstream << str << endl; } return true; }
// 方法二(bug 較多,不推薦)
// 不建立新檔案,直接在原始檔上修改指定字串(覆蓋方法,新字串比原字串長的時候才能使用)。指標位置對應函式(tellg seekg <-> tellp seekp)
bool FixNewFile(fstream &fixstream)
{
	string str;
	size_t cur;
// 記錄讀指標位置 size_t pos = 0; while (getline(fixstream, str)) { pos = str.find("Tom"); if (pos != string::npos) { cur = fixstream.tellg(); size_t len = strlen(str.c_str()) + 2; fixstream.seekp(-1 * len, fstream::cur); // (讀寫指標本來在相同位置),此時寫指標回退到上一行 str.replace(pos, 3, "Lucy"); //fixstream.clear();
fixstream << str; fixstream.seekp(cur); // 寫指標位置還原 continue; } } return true; }
// 主函式
int main()
{
	string file_path = "F:\\mtl_std_lod1.fx";
	string out_path = "F:\\mtl_std_lod1.glsl";
	ifstream instream(file_path); // instream.open(file_path) 預設以ifstream::in開啟
	ofstream outstream(out_path); // outstream.open(out_path) 預設以ostream::out開啟,檔案內容會被丟棄,可使用app模式(寫指標會被定位到檔案末尾)
	FileStringReplace(instream, outstream);
	instream.close();
	outstream.close();

	fstream fixstream(out_path); // fstream 預設以讀寫方式開啟檔案,支援對同一檔案同時讀寫操作
	FixNewFile(fixstream);
	fixstream.close();

	//system("pause");
	return 0;
}