PDA

View Full Version : QTextStream and end of file



timmu
10th September 2012, 12:14
What is the best way to stop QTextStream input at end of file.
This reads past end of file because apaprently the end of row character is considered an entry. What clause to use with QTextStream to detect for that? Normally I would use !file.eof() but this does not work here. My input file consists of several rows of numbers (all rows contain the same number of values).

My code




QFile file(Name); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {exit(1);}
QTextStream my_stream(&file);

while(!my_stream.atEnd())
{

for (k=0; k<100; k++)
{
double readInput;
my_stream >> readInput;
}
}



This would work but it's not elegant:
(and it actually has a problem since one wrong value is read)



bool OK=1;
while(!my_stream.atEnd() && OK)
{

for (k=0; k<100; k++)
{
if(OK)
{
double readInput;
my_stream >> readInput;
}
if(my_stream.atEnd()) OK=0;
}
}


I need to read my file one entry at a time but readLine() wouldn't work since I don't want to convert QString to double every time.

wysota
10th September 2012, 15:18
QFile::atEnd()

timmu
10th September 2012, 15:25
Thanks, Wysota. However, I'm a bit unclear about what you mean. I thought I used atEnd() but in my example it does not work. The for loop still messes up.

wysota
10th September 2012, 15:38
You used QTextStream::atEnd() and not QFile::atEnd().

However it might be that I misunderstood your problem. Here is an alternative:


while(!file.atEnd()) {
stream >> someVariable;
if(stream.status() != QTextStream::Ok) break; // check status before using the data
doSomethingWith(someVariable);
}

timmu
10th September 2012, 15:58
Thanks! I was also wondering how expensive this is



if(stream.status() != QTextStream::Ok) break;


I need to do it very many times (hundreds of millions). How much overhead does it add?

And this is still using QTextStream. So I still need QTextStream?

wysota
10th September 2012, 16:10
You don't need QTextStream if you don't want it. Checking the status is cheap, it's just a variable in the stream object. However using the stream itself already adds some overhead.

amleto
10th September 2012, 18:25
with stl streams, the best usage is normally



while(stream >> var)
{
// do stuff
}


I don't know how well that usage/paradigm works with Qt streams.