Parsing QByteArray

2.3k Views Asked by At

I have a file name into a QByteArray

QString file_name = "icon.jpg";
QByteArray qba1; qba+=file_name;

I have the contents of a file into a QByteArray

QFile file("C:\\Devel\\icon.jpg"); 
if (file.open(QIODevice::ReadOnly)){
     QByteArray content = file.readAll();
}
  1. How to connect the file name and the contents of one variable of type QByteArray?
  2. How to parse this variable QByteArray back to file name and content?
1

There are 1 best solutions below

0
On

Simplest way is to start with the length of the filename, then the filename itself, followed by the data. Parsing the data back is as simple as reading the filename-length first, read the filename, then the data.

QByteArray qbaFileName((const char*)(file_name.utf16()), file_name.size() * 2);

QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);
stream << (int)qbaFileName.size();    // put length of filename on stream
stream << qbaFileName;                // put filename on stream
stream << file.readAll();             // put binary data on stream