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?
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.
open(QFile::ReadOnly | QFile::Text); QTextStream ReadFile(&file); while (! ReadFile. atEnd()) { QString line = ReadFile. readLine(); ui->Output->append(line); } file.
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().
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());
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With