替换文本文件或者二进制文件中的指定字符串
// 方法一
// 将源文件中的特定字符串替换,内容输出到新文件中
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 << 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); // (file_path) 默认以ifstream::in打开
ofstream outstream(out_path); // (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;
}