我需要在文本文件中查找并替换一些文本。我用谷歌搜索并发现最简单的方法是将文件中的所有数据读取到 QStringList,找到并用文本替换确切的行,然后将所有数据写回我的文件。这是最短的方法吗?你能提供一些例子吗? UPD1我的解决方案是:
QString autorun;
QStringList listAuto;
QFile fileAutorun("./autorun.sh");
if(fileAutorun.open(QFile::ReadWrite |QFile::Text))
{
while(!fileAutorun.atEnd())
{
autorun += fileAutorun.readLine();
}
listAuto = autorun.split("\n");
int indexAPP = listAuto.indexOf(QRegExp("*APPLICATION*",Qt::CaseSensitive,QRegExp::Wildcard)); //searching for string with *APPLICATION* wildcard
listAuto[indexAPP] = *(app); //replacing string on QString* app
autorun = "";
autorun = listAuto.join("\n"); // from QStringList to QString
fileAutorun.seek(0);
QTextStream out(&fileAutorun);
out << autorun; //writing to the same file
fileAutorun.close();
}
else
{
qDebug() << "cannot read the file!";
}
原文由 wlredeye 发布,翻译遵循 CC BY-SA 4.0 许可协议
例如,如果所需的更改是将“ou”替换为美式“o”,则
“颜色行为风味邻居”变成“颜色行为风味邻居”,你可以这样做: -
我还没有编译这个,所以代码中可能有错误,但它为您提供了您可以做什么的大纲和大致概念。