【转】从QDataStream向QByteArray中写入数据时的注意点(QT)

时间:2023-12-27 13:53:13

最近发现从QDataStream向QByteArray中写入数据常常是写不进去的,通过查看QT的源码:

【转】从QDataStream向QByteArray中写入数据时的注意点(QT)
QDataStream &operator>>(QDataStream &in, QByteArray &ba)
{
ba.clear();
quint32 len;
in >> len;
if (len == 0xffffffff)
return in; const quint32 Step = 1024 * 1024;
quint32 allocated = 0; do {
int blockSize = qMin(Step, len - allocated);
ba.resize(allocated + blockSize);
if (in.readRawData(ba.data() + allocated, blockSize) != blockSize) {
ba.clear();
in.setStatus(QDataStream::ReadPastEnd);
return in;
}
allocated += blockSize;
} while (allocated < len); return in;
}
【转】从QDataStream向QByteArray中写入数据时的注意点(QT)

发现原来其中有一句:

1
if (in.readRawData(ba.data() + allocated, blockSize) != blockSize) {

它检查读入的数据是不是整数个blockSize,如果不是,那么下面它会将QByteArray清空:

1
ba.clear();

所以如果想从QDataStream读入数据岛QByteArray中,可以采用下面的方法:

【转】从QDataStream向QByteArray中写入数据时的注意点(QT)
QDataStream &operator>>(QDataStream &in, QByteArray &ba)
{
ba.clear();
quint32 len;
in >> len;
if (len == 0xffffffff)
return in; const quint32 Step = 1024 * 1024;
quint32 allocated = 0; do {
int blockSize = qMin(Step, len - allocated);
ba.resize(allocated + blockSize);
if (in.readRawData(ba.data() + allocated, blockSize) < blockSize) {
return in;
}
allocated += blockSize;
} while (allocated < len); return in;
}
【转】从QDataStream向QByteArray中写入数据时的注意点(QT)

最后回过头来看一下将QByteArray写入QDataStream的方法

【转】从QDataStream向QByteArray中写入数据时的注意点(QT)
QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
{
if (ba.isNull() && out.version() >= 6) {
out << (quint32)0xffffffff;
return out;
}
return out.writeBytes(ba, ba.size());
}
【转】从QDataStream向QByteArray中写入数据时的注意点(QT)

其实是将QByteArray中所有的数据都写入QDatStream中,并没有扩展QByteArray的大小到blockSize,

所以针对这种情况,我们在使用QDataStream向QByteArray中读写数据的时候,需要手动将QByteArray

扩展到blockSize(1024*1024)大小。