我想读取一个有几行的文件,然后搜索特定的行,如果找到该行,我想用其他值替换该行,我该怎么做?
这是现在的情况:
#include <string>
using namespace std;
int main()
{
string line;
ifstream myfile( "file.txt" );
if (myfile)
{
while (getline( myfile, line ))
{
if (line == "my_match")
{
//cout << "found";
... here i would like to replace "my_match" with some other value
}
}
myfile.close();
}
else cout << "error";
return 0;
}
最佳答案
我同意 Paul 的观点——Perl 很好:
#!/usr/bin/perl -i.bak
while (<>) {
if (/^my_match$/) {
print "replaced_line\n";
} else {
print "$_";
}
}
-i.bak
将自动替换您正在阅读的文件,并创建一个带有 .bak
扩展名的备份。
sed更好:
sed -i 's/^my_match$/replace_text/' file.txt
但是,在 C 中,为什么不将您的行写入标准输出,而不是重写文件。然后使用文件指令/bash 写入新文件?
如果您必须在 C++ 中执行此操作,读入内存然后写出是一种选择(假设您的文件永远不会太大):
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
string line;
vector<string> buffer;
ifstream in( "file.txt" );
while (getline(in, line)) {
buffer.push_back( (line == "my_match") ? "REPLACED" : line );
}
in.close();
ofstream out("file.txt");
for (vector<string>::iterator it = buffer.begin(); it!=buffer.end(); it++) {
out << *it << endl;
}
return 0;
}
如果您的文件可能太大,您需要写入一个临时文件,然后删除原始文件并重命名临时文件。
关于C++读取文件并替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8861560/