cpp查找文件“change.txt”中的字符串”name“,并替换为”name2“
时间: 2024-08-13 20:09:37 浏览: 102
在C++中,你可以使用`fstream`库来操作文件,包括读取和替换内容。以下是一个简单的示例代码片段,展示了如何查找并替换`change.txt`文件中的特定字符串:
```cpp
#include <fstream>
#include <string>
// 定义要查找和替换的字符串
const std::string searchStr = "name";
const std::string replaceStr = "name2";
void replaceStringInFile(const std::string& filename) {
std::ifstream inputFile(filename, std::ios::in);
if (!inputFile.is_open()) {
std::cerr << "Failed to open file: " << filename << std::endl;
return;
}
std::string line;
std::ofstream outputFile(filename, std::ios::out | std::ios::trunc); // truncates the file before writing
while (std::getline(inputFile, line)) {
size_t pos = line.find(searchStr);
if (pos != std::string::npos) { // 如果找到字符串
line.replace(pos, searchStr.length(), replaceStr); // 替换字符串
}
outputFile << line << "\n"; // 写入新行
}
inputFile.close();
outputFile.close();
if (outputFile.is_open()) {
std::cout << "String replaced successfully in " << filename << "." << std::endl;
} else {
std::cerr << "Could not close the output file." << std::endl;
}
}
int main() {
replaceStringInFile("change.txt");
阅读全文