问题:QDataStream中写入的数据比QByteArray多了4个byte。
仔细看了下,这个4个byte表示的是QByteArray的数据长度。
转载官方文档:https://doc.qt.io/qt-6/qdatastream.html
QDataStream &QDataStream::readBytes(char *&s, uint &l)
Reads the buffer s from the stream and returns a reference to the stream.
The buffer s is allocated using
new []
. Destroy it with thedelete []
operator.The l parameter is set to the length of the buffer. If the string read is empty, l is set to 0 and s is set to
nullptr
.The serialization format is a quint32 length specifier first, then l bytes of data.
int QDataStream::readRawData(char *s, int len)
Reads at most len bytes from the stream into s and returns the number of bytes read. If an error occurs, this function returns -1.
The buffer s must be preallocated. The data is not decoded.
QDataStream &QDataStream::writeBytes(const char *s, uint len)
Writes the length specifier len and the buffer s to the stream and returns a reference to the stream.
The len is serialized as a quint32, followed by len bytes from s. Note that the data is not encoded.
int QDataStream::writeRawData(const char *s, int len)
Writes len bytes from s to the stream. Returns the number of bytes actually written, or -1 on error. The data is not encoded.
注意到 << 操作符 也是用的writeBytes同样的逻辑
QDataStream &QDataStream::operator<<(const char *s)
This is an overloaded function.
Writes the '\0'-terminated string s to the stream and returns a reference to the stream.
The string is serialized using
writeBytes()
.
所以会多写一个int32在开始。
为了避免这种情况的产生,可以调用对应 W/R RawData 方法。
标签:QByteArray,读取,stream,buffer,bytes,len,returns,QDataStream From: https://www.cnblogs.com/crazyghostvon/p/17582504.html