QT:查找和替换文件中的文本

新手上路,请多包涵

我需要在文本文件中查找并替换一些文本。我用谷歌搜索并发现最简单的方法是将文件中的所有数据读取到 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 许可协议

阅读 1.2k
1 个回答

例如,如果所需的更改是将“ou”替换为美式“o”,则

“颜色行为风味邻居”变成“颜色行为风味邻居”,你可以这样做: -

 QByteArray fileData;
QFile file(fileName);
file.open(stderr, QIODevice::ReadWrite); // open for read and write
fileData = file.readAll(); // read all the data into the byte array
QString text(fileData); // add to text string for easy string replace

text.replace(QString("ou"), QString("o")); // replace text in string

file.seek(0); // go to the beginning of the file
file.write(text.toUtf8()); // write the new text back to the file

file.close(); // close the file handle.

我还没有编译这个,所以代码中可能有错误,但它为您提供了您可以做什么的大纲和大致概念。

原文由 TheDarkKnight 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题