3

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

3 回答 3

8

例如,如果所需的更改是将“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.

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

于 2013-07-29T09:28:25.717 回答
1

为了完成接受的答案,这是一个经过测试的代码。需要使用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();
于 2022-02-14T16:41:43.550 回答
-1

我一直在使用带有批处理文件和 sed.exe 的正则表达式(来自 gnuWin32,http ://gnuwin32.sourceforge.net/ )。它足以替换单个文本。顺便说一句,那里没有简单的正则表达式语法。如果您想获得一些脚本示例,请告诉我。

于 2013-07-29T11:18:30.003 回答