How to read Binary data from file using QDataStream in QT C++

  c++, c++11, file, qt, qt5

if you look in the documentation of QT. You can use readBytes or readRawBytes to read the binary data from a file. I am comfortable in any case, either reading the data from file or stream.
In case of readBytes – Reads the buffer s from the stream and returns a reference to the stream.
In case of readRawBytes – Reads L (length) bytes from the stream into s(buffer char*) and returns the number of bytes read.

void readBinary(QString path)
{
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Could not open bin file for reading";
        return;
    }

    QDataStream in(&file);
    char *data = new char[30];

    qint32 bytes = in.readRawData(data, 30);
    //in >> data;
    qInfo() << "bytes read: " << bytes;
    qInfo() << data;

    file.close();
}

It shows no of bytes reads but not showing binary data on screen.

  1. What I am missing here?
  2. Do we need to do serialization/de-serialization of binary data? In another words marshelling/un-marshelling of data. because I have read in offical documentation encoding/decoding you need to take care of by own and need to set version of QT while reading/writing the data in file.
  3. How do we write back to the file/stream.
  4. If we have another to read/write the data directly from file.

for you reference – consider the snippet of binary data in file as mentioned below.

00000000: 0000 0520 a52a 0108 8520 0108 9320 0108  ... .*... ... ..
00000010: 9920 0108 9f20 0108 a520 0108 0000 0000  . ... ... ......

Source: Windows Questions C++

LEAVE A COMMENT