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
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 to share