How to search for a string in a text file using Qt

I am trying to find a line in a text file; my goal is to write it only if it is not already written inside my text file.

Here's my function (I don't know how to put it inside the while loop):

QFile MyFile("text.txt");
MyFile.open(QIODevice::ReadWrite);
QTextStream in (&MyFile);

while(!MyFile.atEnd())
  { //do something to search string inside }

MyFile.close();

      

How can i do this? From the Qt help, the "contains" method only works with const; can i use it to find my string?

+3


source to share


2 answers


You can do the following:



[..]
QString searchString("the string I am looking for");
[..]
QTextStream in (&MyFile);
QString line;
do {
    line = in.readLine();
    if (!line.contains(searchString, Qt::CaseSensitive)) {
        // do something
    }
} while (!line.isNull());

      

+5


source


In case of a small file

QFile MyFile("text.txt");
MyFile.open(QIODevice::ReadWrite);
QTextStream in (&MyFile);
const QString content = in.readAll();
if( !content.contains( "String" ) {
//do something
}
MyFile.close();

      



To avoid repeating other answers in case of large files, do as vahancho suggested

+2


source







All Articles