简体   繁体   中英

Parsing QByteArray

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM