gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:23:36 25 4
gpt4 key购买 nike

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

最佳答案

如果需要更改,例如将“ou”替换为美式“o”,这样

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

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.

我还没有编译这个,所以代码中可能有错误,但它给了你一个大纲和你可以做什么的总体思路。

关于c++ - QT:查找和替换文件中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17919778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com