PDA

View Full Version : Serialization with QDataStream



Eduardo Huerta
12th December 2019, 03:51
Hi,
How can I do the serialization of a QString?
I have executed the example code that is in the QDataStream class, but it does not do the serialization of the QString, only of the integer, the output in the file is the following: the answer *
And the code is as follows:

QFile file("/Users/eduardo/My Cloud/Programas/readFileLineToLine12/dat1.txt");
if (!file.open(QIODevice::WriteOnly/* | QIODevice::Append*/)) {
QMessageBox::information(this, tr("Unable to open file"), file.errorString());
return;
}
QDataStream out(&file);
out.setVersion(QDataStream::Qt_5_4);
out << QString("the answer is");
out << (qint32)42;
file.flush();
file.close();

Thanks a lot

ChrisW67
12th December 2019, 08:21
How can I do the serialization of a QString?
Like you have done. QDataStream serialiszs in a binary format. Your code outputs this binary data into the file (offsets and data in hex):


$ od -A x -tx1 dat1.bin
000000 00 00 00 1a 00 74 00 68 00 65 00 20 00 61 00 6e
000010 00 73 00 77 00 65 00 72 00 20 00 69 00 73 00 00
000020 00 2a

The QString is the length in bytes (00 00 00 1a i.e. 26 ) followed by the bytes that make up the 13 chars of text "the answer is".
The integer 42 is the four bytes 00 00 00 2a
Total file length is 34 bytes.

If you treat the binary file as text (like you have) then the first five bytes are non-printable, followed by "t", another non-printable, "h" ..., and the last byte is 0x42 corresponding to an asterisk.


If you want to see the text followed by 42, like "the answer is 42", then you should look at QTextStream.