以下是使用C++读写文件并替换子文本的示例代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string filePath = "example.txt"; // 文件路径
string searchText = "Hello"; // 要替换的子文本
string replaceText = "World"; // 替换后的文本
// 读取文件内容
ifstream fileIn(filePath);
string content((istreambuf_iterator<char>(fileIn)), istreambuf_iterator<char>());
fileIn.close();
// 替换子文本
size_t foundPos = content.find(searchText);
while (foundPos != string::npos) {
content.replace(foundPos, searchText.length(), replaceText);
foundPos = content.find(searchText, foundPos + replaceText.length());
}
// 写入替换后的内容
ofstream fileOut(filePath);
fileOut << content;
fileOut.close();
cout << "替换完成!" << endl;
return 0;
}
请注意,上述代码将会替换文件中所有匹配到的子文本。如果你只想替换第一个匹配到的子文本,可以将 foundPos = content.find(searchText, foundPos + replaceText.length());
改为 foundPos = content.find(searchText, foundPos + 1);
。
此外,还请确保你有读取和写入文件的权限,并且替换的子文本在文件中确实存在。
没有回复内容