PDA

View Full Version : QFile::Seek() not working



derrickbj
5th October 2011, 18:30
Hello,

I may not be doing something correctly, but can't see any other posts related to my issue. I'm reading in a file and searching for specific text. When Text is found, I break out of my while (!atEnd()) loop and change the position back to 0 by QFile::seek(0). It doesn't appear to work. Moreover, I had to do some odd behavior in order to make it work:

Code that doesn't work:



QFile file(myFile)
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
QTextStream in(&file)
while (!(in.atEnd())) {
QString str = in.readLine();
//...some other code....
if (str == text_to_find) break;

}
if (!file.seek(0)) return;

//loop through map and find each item in file, displaying which ones exist
int i;
for (i=itemsMap.begin(); i != itemsMap.end(); ++i) {
QString cmp = i.value();
while (!file.atEnd()) {
str = in.readLine();
if (str == cmp) std::cout << "comparison found";
}
if (!file.seek(0)) return;
}


Code that works:




QFile file(myFile)
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
QTextStream in(&file)
while (!(in.atEnd())) {
QString str = in.readLine();
//...some other code....
}
if (!file.seek(0)) return;
str = in.readLine()
if (!file.seek(0)) return;

//loop through map and find each item in file, displaying which ones exist
int i;
for (i=itemsMap.begin(); i != itemsMap.end(); ++i) {
QString cmp = i.value();
while (!file.atEnd()) {
str = in.readLine();
if (str == cmp) std::cout << "comparison found";
}
if (!file.seek(0)) return;
}


For some reason, if I put the break statement back in the first while loop, the 2nd while loop (within the first iteration through the for loop) picks up where the previous while loop left off. If I comment out the break, as in the second code snippet, it still doesn't seem to do the job. After the first while loop, I have to do a seek(0), then read in a line, then do another seek(0). When debugging, it seems that it treats the first line in the file as the last line of the file....???

norobro
5th October 2011, 19:13
You are operating on a stream not the file, so try:
in.seek(0)
Also line 16 should be:
while (!in.atEnd())

derrickbj
5th October 2011, 20:14
That did the trick, thanks so much! This was driving me nuts