6

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?

Noam M
  • 3,156
  • 5
  • 26
  • 41
LittleSaints
  • 391
  • 1
  • 6
  • 19

2 Answers2

9

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());
vahancho
  • 20,808
  • 3
  • 47
  • 55
  • 1
    This will only work accurately if the searchString doesn't contain a new line character. – LovesTha Apr 30 '16 at 10:15
  • 1
    The commands used seem to be valid, but the program flow logic doesn't: You _do something_ for every line which does not contain the string. You should rather toggle a boolean value at the _do something_ point of your code, and break the loop. And then, check this bool outside the loop to conditionally _do something_. – philipp Mar 14 '17 at 12:48
5

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

Robert Wadowski
  • 1,407
  • 1
  • 11
  • 14