Reputation: 419
I'm trying to search for a string in a text file; my aim is to write it only if it isn't already written inside my text file.
Here's my function (I don't know how to put 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 that? From Qt's Help, method "contains" works with const variable only; can I use it to look for my string?
Upvotes: 6
Views: 16859
Reputation: 1427
In case of not large 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 not repeat other answers in case of larger files do as vahancho suggested
Upvotes: 5
Reputation: 21258
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());
Upvotes: 9