[SOLVED] QT: Finding and replacing text in a file


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))
        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
    QTextStream out(&fileAutorun);
    out << autorun; //writing to the same file
    qDebug() << "cannot read the file!";


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.

Answered By – TheDarkKnight

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *