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

QT: Finding and replacing text in a file

本文关键字:文本 文件 替换 查找 QT      更新时间:2023-10-16

我需要查找并替换文本文件中的一些文本。我在谷歌上搜索了一下,发现最简单的方法是将文件中的所有数据读取到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!";
}

如果所需的更改,例如用美国的"o"替换"ou",则

"颜色行为味道邻居"变成"颜色行为气味邻居",你可以这样做:-

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.

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

要完成接受的答案,这里有一个经过测试的代码。需要使用QByteArray而不是QString

QFile file(fileName);
file.open(QIODevice::ReadWrite);
QByteArray text = file.readAll();
text.replace(QByteArray("ou"), QByteArray("o"));
file.seek(0);
file.write(text);
file.close();

我已经将regexp与批处理文件和sed.exe(来自gnuWin32,http://gnuwin32.sourceforge.net/)。它足以替换一个文本。顺便说一句,这里没有一个简单的regexp语法。如果你想得到一些脚本的例子,请告诉我。