Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QT: Finding and replacing text in a file

Tags:

c++

text-files

qt

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!";
}
like image 368
wlredeye Avatar asked Sep 17 '25 22:09

wlredeye


1 Answers

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.

like image 165
TheDarkKnight Avatar answered Sep 19 '25 10:09

TheDarkKnight