c++qtqdatastream

read / write on byte array by QDataStream


i have byte image array i want to write this byte array to another byte array with add some another value on second byte array , i'm using this code but i think something is wrong

 QByteArray byteArray;

 QDataStream ds(&byteArray,QIODevice::ReadWrite);

 ds<<(qint32)20;

 ds<<bArray;

 qint32 code;

 ds>>code;

when i trace ds>>code it is always have 0 value but in fact it must have 20 value and i used ds.resetStatus(); but it return 0 value again


Solution

  • I suspect that QDataStream::operator<< functions sets some sort of pointer/iterator/index to point to the next location where they can start inserting data when the next call is made. QDataStream::operator>> probably starts to read from the same location.

    QDataStream::resetStatus() does not change the position from where the object reads/writes. It merely resets the status to QDataStream::Ok to allow you to read from the stream after an error has occurred.

    You can use two QDataStream objects -- one for writing to the QByteArray and the other for reading from the same QByteArray.

    QByteArray byteArray;
    
    QDataStream ds_w(&byteArray,QIODevice::WriteOnly);
    QDataStream ds_r(&byteArray,QIODevice::ReadOnly);
    
    ds_w << (qint32)20;
    
    ds_w << bArray;
    
    qint32 code;
    
    ds_r >> code;