【问题标题】:Why QDatastream is not giving the correct output为什么 QDatastream 没有给出正确的输出
【发布时间】:2020-04-15 06:19:24
【问题描述】:

在给定的代码中,我首先在流中插入 1 个数字,然后将该值放入名为 Variable 的测试中。

当我打印变量时,我得到的输出是 0 而不是 1。

这是代码。

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

【问题讨论】:

    标签: qt qt5 qdatastream


    【解决方案1】:

    当您像以前一样创建QDataStream 时,QBuffer 将用作内部QIODevice(请参阅https://doc.qt.io/qt-5/qdatastream.html#QDataStream-2)。

    QBuffer 不会像 FIFO 队列那样工作,它只会记住它完成上一次操作的时间,并会从该点开始另一个操作。

    当您向流中写入内容时,“位置”将在新数据之后移动。由于缓冲区一开始是空的,光标将指向数据的末尾,任何读取尝试都会失败。如果您想阅读您写的内容,您必须将光标移回。

    也许下面的例子会让这个想法更清楚:

    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();
    

    输出:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-28
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      相关资源
      最近更新 更多