PDA

View Full Version : Reading QByteArray from QDataStream Qt3.3



high_flyer
1st April 2006, 09:53
Hi,

I am overloading the operator>>() and operator<<() for QDataStream to serialize my own data blocks.
For writing in to binary file:


QDataStream & operator<<( QDataStream &s, AtmosBBlock &data)
{
QByteArray b_data;
b_data.resize(sizeof(data));
memcpy(b_data.begin(),&data,sizeof(data));
s<<b_data;
return s;
}

For reading from binary file:


QDataStream & operator>>( QDataStream &s, AtmosBBlock &data)
{
QByteArray b_data;
b_data.resize(sizeof(data));
s>>b_data;
memcpy(&data,b_data.begin(),sizeof(data));
return s;
}

The problem is, that s>>b_data is resulting in a 0 sized QByteArray, and I don't understand why.
To check if the problem is in the written file I did the following:


QDataStream & operator>>( QDataStream &s, AtmosBBlock &data)
{
QByteArray b_data;
b_data.resize(sizeof(data));
s.readRawBytes((char*)&b_data,sizeof(b_data));
memcpy(&data,b_data.begin(),sizeof(data));
return s;
}

This reads the file correctly with the previously written data.

Any idea why s>>b_data returns a 0 sized QByteArray?

Thanks in adavance.

wysota
1st April 2006, 12:14
I think >> expects not only the data itself but also a field which tells how much data to read. ReadRawBytes on the other hand takes the size as its argument. Those two calls are not equivalent. I understand that if you write something with << you should be able to read it with >>, but looks like it fails here. It could be that sizeof() returns invalid size here. Why do you use memcpy here? What is AtmosBBlock?

high_flyer
1st April 2006, 20:23
I think >> expects not only the data itself but also a field which tells how much data to read.
How do you mean?
The API does not include any extra parameter just a QBayteArray:

QDataStream & operator>> ( QDataStream & s, QByteArray & a )

Reads a byte array into a from the stream s and returns a reference to the stream.

I thought it could be that QDataStream uses QBatesArray::size() to detrmine the amount of bytes to read, which is why I resize it before the read.
But it doesn't work.
I am well aware that readRawBytes and >> are different, but I still can't understand why >> with a QByteArray does not work, when according to the docs it should (unless I am missing here somthing in the docs).

AtmosBBlock is a struct with natural types (Q_UINT8 and Q_UINT16)

Thanks.