Search code examples
fileqtstreamseekfile-read

Uncharacteristic file-read operation using QTextStream in Linux


I am using linux platform (Ubuntu) and QT4.7.4 ,

first, I create a test file "test.txt" using vi , just write 100000 lines "1234567890" in it,

Then I compile & run the codes below, to my supervising ,it enter infinite loop ,

any ideas about it ? Thanks!

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QString str;

    QFile file("./test.txt");
    if ( file.open(QIODevice::ReadOnly | QIODevice::Text) ) {

        QTextStream ts( &file );
        while(!ts.atEnd()) {
            str = ts.read(10240);
            qDebug()<<"s:"<<ts.status()<<":"<<ts.atEnd()<<":"<<str.count()<<":"<<ts.pos();

        }
    }
    return app.exec();
}

here is the qdebug output:

s: 0 : false : 10240 : 10240 
s: 0 : false : 10240 : 20480 
s: 0 : false : 10240 : 51200 
s: 0 : false : 10240 : 112640 
s: 0 : false : 10240 : 235520 
s: 0 : false : 10240 : 481280 
s: 0 : false : 10240 : 972800 
s: 0 : false : 10240 : -1 
s: 0 : false : 10240 : -1 
s: 0 : false : 10240 : -1 
s: 0 : false : 10240 : -1 
s: 0 : false : 10240 : -1 
s: 0 : false : 10240 : -1 
s: 0 : false : 10240 : -1 
....

here are some infos about test.txt

$du  -sh test.txt 
1.1M    test.txt

$wc -c test.txt 
1100011 test.txt

$du -S test.txt 
1076    test.txt

Solution

  • This was a bug in QTextStream::pos, which prevented to use pos() with files bigger than 16KB (I think), it seems to have been fixed somewhere between Qt 4.7 and 4.8.

    But anyway, using QTextStream::pos() inside that loop is terribly impacting the reading speed, so, you should avoid it.