赞
踩
我在使用QByteArray保存数据到QDataStream时,二进制文件中,发现头部多出4个字节,就像这样。
网上搜了一些文章,说这4个字节表示数据存储的长度,我比较关心怎样才可以去掉这4个字节,网上方法不详。
于是我调试了一下Qt源码,发现是这样的。
QDataStream的writeBytes接口实现中,会先写入数据长度len,所以调用writeBytes就会导致此现象。
- /*!
- Writes the length specifier \a len and the buffer \a s to the
- stream and returns a reference to the stream.
-
- The \a len is serialized as a quint32, followed by \a len bytes
- from \a s. Note that the data is \e not encoded.
-
- \sa writeRawData(), readBytes()
- */
- QDataStream &QDataStream::writeBytes(const char *s, uint len)
- {
- CHECK_STREAM_WRITE_PRECOND(*this)
- *this << (quint32)len;// write length specifier
- if (len)
- writeRawData(s, len);
- return *this;
- }
QByteArray在使用<<操作符输入到QDataStream时,会调用writeBytes,导致多出4个字节。
- QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
- {
- if (ba.isNull() && out.version() >= 6) {
- out << (quint32)0xffffffff;
- return out;
- }
- return out.writeBytes(ba.constData(), ba.size());
- }
然后我发现,使用writeRawData可以避免写入头4个字节的数据。
除了QByteArray,这些类使用<<对QDataStream输入时,也会多出4个字节。
QBitArray
QPicture
const char*
如果只希望保存原始数据,就需要先从数据源中取出数据,再直接调用QDataStream的writeRawData接口即可。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。