c++qtqt5qdatastream

QT read/write from QDataStream


I think i am having a fundamental misunderstanding of how all of this works, I am trying to combine 2 hexfiles in my QDataStream and then output them to a new QFile.

QFile filea( file1 );
QFile fileb( file2 );
QByteArray ba;
QDataStream ds(ba);
ds << filea.readAll();
ds << fileb.readAll();
QFile result("C:/Users/Aaron/Desktop/mergedfile.txt");
result.open(QIODevice::ReadWrite);
result.write(ba);

The result is just an empty file, any suggestions?


Solution

  • You have the following errors:

    QDataStream::QDataStream(const QByteArray &a)

    Constructs a read-only data stream that operates on byte array a. Use QDataStream(QByteArray*, int) if you want to write to a byte array.

    Since QByteArray is not a QIODevice subclass, internally a QBuffer is created to wrap the byte array.

    And since the QByteArray is read only because it is not the appropriate constructor, you must use the other constructor:

    QDataStream::QDataStream(QByteArray *a, QIODevice::OpenMode mode)

    Constructs a data stream that operates on a byte array, a. The mode describes how the device is to be used.

    Alternatively, you can use QDataStream(const QByteArray &) if you just want to read from a byte array.

    Since QByteArray is not a QIODevice subclass, internally a QBuffer is created to wrap the byte array.

    Using the above we obtain the following:

    QFile filea( file1 );
    QFile fileb( file2 );
    QFile result("C:/Users/Aaron/Desktop/mergedfile.txt");
    
    if(filea.open(QIODevice::ReadOnly) && fileb.open(QIODevice::ReadOnly) && result.open(QIODevice::WriteOnly)){
        QByteArray ba;
        QDataStream ds(&ba, QIODevice::ReadWrite);
        ds << filea.readAll();
        ds << fileb.readAll();
        result.write(ba);
        result.flush();
    }