3
votes

I need to find and replace some text in the text file. I've googled and found out that easiest way is to read all data from file to QStringList, find and replace exact line with text and then write all data back to my file. Is it the shortest way? Can you provide some example, please. UPD1 my solution is:

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
you should try something, and post the code if you fail ...Kai Walz

3 Answers

8
votes

If the required change, for example is to replace the 'ou' with the american 'o' such that

"colour behaviour flavour neighbour" becomes "color behavior flavor neighbor", you could do something like this: -

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.

I haven't compiled this, so there may be errors in the code, but it gives you the outline and general idea of what you can do.

1
votes

To complete the accepted answer, here is a tested code. It is needed to use QByteArray instead of 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();
-1
votes

I've being used regexp with batch-file and sed.exe (from gnuWin32, http://gnuwin32.sourceforge.net/). Its good enough for replace one-single text. btw, there is not a simple regexp syntax there. let me know If you want to get some example of script.