QBuffer flush



  • I have a weird problem with Read/Write to a QBuffer at the same time. For this example I'm reading data from a binary file.

    @int size = 1000;
    char *binaryData = new char[size];
    // Add some binary data to the char array

    QBuffer *buffer = new QBuffer();
    mBuffer->open(QIODevice::ReadWrite);
    buffer->write(QByteArray::fromRawData(binaryData, size));

    char *newData = new char[size];
    mBuffer->read(newData, size);
    mBuffer->close();@

    So far so good. One would now expect the data from newData and binaryData to be the same (or am I wrong). However the data from the 2 arrays are NOT the same. I've played arround with a all the read/write functions of QBuffer, with the same problem. After a while I found the following solution:

    @int size = 1000;
    char *binaryData = new char[size];
    // Add some binary data to the char array

    QBuffer *buffer = new QBuffer();
    mBuffer->open(QIODevice::WriteOnly); // or QIODevice::ReadWrite, doesn't matter
    buffer->write(QByteArray::fromRawData(binaryData, size));
    mBuffer->close();

    mBuffer->open(QIODevice::ReadOnly); // or QIODevice::ReadWrite, doesn't matter
    char *newData = new char[size];
    mBuffer->read(newData, size);
    mBuffer->close();@

    Now the 2 arrays are the same. So I have to close the array after writing and open it again when I want to read. This seems to me like a flush-type of problem. Does QBuffer somehow "flush" the data when it is closed, or why am I not able to read/write at the same time?

    I've also found really old Qt API documentations where there was a flush() function, so why was it ermoved?



  • I think I'm able to answer my own question. Whenever I read, a pointer to the "current" position is moved on (however the Qt docs don't say anything about this). So everytime I'm finnished writing/reading I have to move this "pointer" back for the amount of data I've written/read by using seek().


  • Moderators

    That is a somewhat expensive way to get data from binaryData into newData. Why don't you use qMemCopy from qglobal.h? That one is undocumented, but has been around for ages, so it is unlikely to go away.

    I would recommend using QByteArrays to begin with, avoiding possible buffer overflow issues (QByteArray garantees that there is a trailing \0 char) that frequently happen with those raw chunks of memory.



  • Thanks, I've now switched over to QByteArray.
    I've not mentioned that I actually want to analyse every byte I read, so it will be expensive anyway.


  • Moderators

    There still is no need to do expensive stuff needlessly just because you need to do other expensive stuff anyway.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.