Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 293
LittleSaints Avatar asked Jul 13 '15 13:07

LittleSaints


People also ask

How do you search a file for a specific string of text?

You need to use the grep command. The grep command or egrep command searches the given input FILEs for lines containing a match or a text string.

How do I display a text file in Qt?

open(QFile::ReadOnly | QFile::Text); QTextStream ReadFile(&file); while (! ReadFile. atEnd()) { QString line = ReadFile. readLine(); ui->Output->append(line); } file.

What is QFile QT?

QFile is an I/O device for reading and writing text and binary files and resources. A QFile may be used by itself or, more conveniently, with a QTextStream or QDataStream. The file name is usually passed in the constructor, but it can be set at any time using setFileName().


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());
like image 68
vahancho Avatar answered Sep 21 '22 18:09

vahancho


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

like image 26
Robert Wadowski Avatar answered Sep 23 '22 18:09

Robert Wadowski