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, 3, "Jerry"); // 将Tom替换为Jerry
			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, "Jerry");
			//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;
}
  • 11
    点赞
  • 72
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值