我想读一个有几行的文件,然后搜索一个特定的行,如果找到该行,我想用其他一些值替换该行,我该怎么办?
#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;
}
答案 0 :(得分:2)
我同意保罗 - 佩尔很好:
#!/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中,为什么不将行写入stdout,而不是重写文件。然后使用文件路由/ 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;
}
如果您的文件太大,则需要写入临时文件,然后删除原始文件并重命名临时文件。
答案 1 :(得分:0)
逐行读取文件到向量。更改要更改的行,然后删除原始文件,创建一个新文件并将所有内容写回来。
答案 2 :(得分:0)
如果您想要了解如何使代码更整洁,Code Review就是您想要的位置。
假设您正在使用标准输入和输出,并且将使用不同的语言进行重定向:是的,您正在做的是一种可能的解决方案。你没有告诉我们你想用它替换它,但是下面应该做得很好:
if (line == "my match")
std::cout << "my replacement\n";
else
std::cout << line << '\n';
我要说的最大的问题是它不是非常通用的;如果您只想根据更复杂的谓词来匹配一行,那么最好为此编写一个专用函数(或正则表达式);同样的替换取决于线路。例如,在你的循环中你可以:
std::cout << make_replacement(line);
然后你可以定义:
std::string make_replacement(std::string const& line) {
// some logic to construct a new string based on the line
}
请注意,这会为每一行创建一个副本,这可能很昂贵(取决于要求和文件大小)。