Search code examples
qtqt5qdatastream

Why QDatastream is not giving the correct output


In the given code i am first inserting 1 number in the stream and than i am putting that value in a test named Variable.

when i print the variable i get the output as 0 instead of 1.

This is the code.

    QByteArray data; 
    QDataStream stream(&data, QIODevice::ReadWrite);
    stream << 1;
    int test;
    stream >> test;
    qDebug() << test;

Solution

  • When you create the QDataStream like you did, the QBuffer will be used as internal QIODevice (see https://doc.qt.io/qt-5/qdatastream.html#QDataStream-2).

    QBuffer won't work like a FIFO queue, its simply remembers when it finished last operation and will start another operation from that point.

    When you wrote something to your stream the "position" will be moved after the new data. Due to the fact that the buffer was empty at the beginning, the cursor will point at the end of your data and any read attempts will fail. If you want to read what you wrote, you will have to move the cursor back.

    Maybe following example will make this idea clearer:

    QByteArray data;
    QDataStream stream(&data, QIODevice::ReadWrite);
    stream.setByteOrder(QDataStream::LittleEndian);
    
    const std::uint32_t input = 0x01020304; // 0x01020304 = 16909060
    
    qDebug() << "Device pos before write: " << stream.device()->pos();
    stream << input;
    qDebug() << "Device pos after write: " << stream.device()->pos();
    
    qDebug() << "data content after write: " << data;
    
    stream.device()->seek(0);
    qDebug() << "Device pos after seek: " << stream.device()->pos();
    std::uint32_t test;
    stream >> test;
    qDebug() << "Read: " << test;
    qDebug() << "Device pos after read: " << stream.device()->pos();
    

    Output:

    Device pos before write:  0
    Device pos after write:  4
    data content after write:  "\x04\x03\x02\x01"
    Device pos after seek:  0
    Read:  16909060
    Device pos after read:  4