c++qtqtextstream

QTextStream messing its position pointer


I'm writing a parser for a text file, but QTextStream seems to be missing something. I'm using Qt 5.4.1, and the code is single-threaded, if that matters.

This is the method:

const Event* AviLogFile::nextEvent() {                                          
    qDebug() << "Entering nextEvent()";                                         
    qDebug() << "m_file.pos() before QTextStream: " << m_file.pos();            
    QTextStream in(&m_file);                                                    
    qDebug() << "m_file.pos() after QTextStream: " << m_file.pos();             
    qDebug() << "in.pos(): " << in.pos();                                       
    Event* ev = 0;                                                              

    while (!in.atEnd() && ev == 0) {                                            
        QString line = in.readLine();                                           
        qDebug() << "(inside loop) m_file.pos(): " << m_file.pos();             
        qDebug() << "(inside loop) in.pos(): " << in.pos();                     
        ev = parseEvent(line);                                                  
    }                                                                           

    m_currentEvent = ev;                                                        
    if (!ev) {                                                                  
        qDebug() << "in.AtEnd: " << in.atEnd() << ". file.atEnd: " << m_file.atEnd();
    }                                                                           
    return ev;                                                                  
}

I'm calling it in a loop. The first call works fine, but at the second one, I get this output:

Entering nextEvent()
m_file.pos() before QTextStream:  2244
m_file.pos() after QTextStream:  2244
in.pos():  2244
(inside loop) m_file.pos():  18628
(inside loop) in.pos():  65

As you can see, the QTextStream and QFile internal pointers are fine before entering the loop, but completely messed up inside the loop.

Any idea on what is happening here?


Solution

  • There are several standing bugs regarding using QTextStream::pos() with an IO device underneath. Many of them are "unresolved" or "won't fix" and their reproducer case looks exactly as your problem.

    I suggest to avoid relying on that function (plus, citing from the documentation of QTextStream:

    Because QTextStream is buffered, this function may have to seek the device to reconstruct a valid device position.

    it would also render things slow during your loop).

    More on this can also be found here