QT: Finding and replacing text in a file

16,005

Solution 1

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.

Solution 2

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();
Share:
16,005
wlredeye
Author by

wlredeye

Updated on June 30, 2022

Comments

  • wlredeye
    wlredeye almost 2 years

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