2013-07-29 83 views
2

我需要查找并替换文本文件中的某些文本。我搜索了一下,发现最简单的方法是从文件中读取所有数据到QStringList,找到并用文本替换确切的行,然后将所有数据写回到我的文件。这是最短的路吗?你能提供一些例子吗? UPD1我的解决方案是:QT:查找并替换文件中的文本

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!"; 
} 
+3

你应该尝试一下,并发布代码,如果你失败... –

回答

2

若要求的变化,例如是替代“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. 

我没有编这一点,所以有可能是代码中的错误,但它给你的你可以做什么的轮廓和总体思路。

+0

谢谢!但是如果我需要替换我不知道的字符串字符串长度呢? – wlredeye

+0

你能举个例子说明你的意思吗? – TheDarkKnight

+0

我为此发布了我的解决方案,但问题是如何在阅读之后但写入之前清除文件内容?因为如果我有不同长度的文件,此解决方案不起作用 – wlredeye

0

我已经用批处理文件和sed.exe(来自gnuWin32,http://gnuwin32.sourceforge.net/)使用regexp。它足够替代单一文本。 顺便说一句,那里没有简单的正则表达式语法。让我知道如果你想得到一些脚本的例子。

+0

我想可能这不是“正确的程序员方式”使用外部应用程序? :)但它是有用的,谢谢! – wlredeye

+0

完全同意你的看法。有时候这样的方式可能会非常有帮助。我正在使用这种方式来快速自动“修补”vcxproj和vdproj文件。 –

+0

你能提供一些简单的脚本例子吗? – wlredeye