【转】从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;
}
发现原来其中有一句:
1
|
if (in.readRawData(ba.data() + allocated, blockSize) != blockSize) { |
它检查读入的数据是不是整数个blockSize,如果不是,那么下面它会将QByteArray清空:
1
|
ba.clear(); |
所以如果想从QDataStream读入数据岛QByteArray中,可以采用下面的方法:
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;
}
最后回过头来看一下将QByteArray写入QDataStream的方法
QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
{
if (ba.isNull() && out.version() >= 6) {
out << (quint32)0xffffffff;
return out;
}
return out.writeBytes(ba, ba.size());
}
其实是将QByteArray中所有的数据都写入QDatStream中,并没有扩展QByteArray的大小到blockSize,
所以针对这种情况,我们在使用QDataStream向QByteArray中读写数据的时候,需要手动将QByteArray
扩展到blockSize(1024*1024)大小。