Writing regular text data to a QDataStream (or writing binary data to QTextStream)
-
Title, for my code I've got a binary file format which has mostly binary data but also has null-terminated text in it for a name/description.
So, I tried writing it with QTextStream, which resulted in some really weird results. I was trying to write a 12-byte long vector (specifically, a
Botan::secure_vector<uint8_t>
. I tried this by converting it to a QByteArray, but it wrote it as if it was in its"\xXX"
form which didn't work of course. I tried looping through the vector, and writing each individual byte to it as aQChar
, but this was even stranger. UsingqDebug
, the output of the IV itself wasstd::vector(164, 204, 3, 146, 159, 255, 163, 30, 59, 11, 162, 211)
, but when I read the file back, I getstd::vector(194, 164, 195, 140, 3, 194, 146, 194, 159, 195, 191, 239, 191, 189)
. I have no idea what could possibly cause this.I also tried writing it as a
const char *
. In this case, before, it wasstd::vector(244, 204, 239, 205, 113, 104, 26, 15, 181, 0, 244, 219)
and after reading it back, I gotstd::vector(239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189)
. Yet again, what's going on here? It's literally just a stream of239, 191, 189
. Sometimes it would put that sequence before every single byte.So yeah, after that, I tried QDataStream, which worked except that all the text was serialized as a QString, so 4 bytes of length then the contents. I didn't want this and just wanted to write the text itself (and of course, null-terminate it). And I couldn't get anything to work, I tried writing as
const char *
andQByteArray
.Now that that's out of the way, what exactly should I do here?
-
When you don't want to use the format of QDataStream then use ofstream or something else. The format of QDataStream is fixed and can not be changed. The output of a QDataStream is also only to be used with QDataStream and nothing else. So either accept the 4 bytes or do it by your own / with another class.
-
@swirl said in Writing regular text data to a QDataStream (or writing binary data to QTextStream):
Now that that's out of the way, what exactly should I do here?
If you want a custom format, you have to write it out by yourself. QDataStream needs those bytes to know the length of the string later on when reading the data.
-
@Christian-Ehrlicher wdym "write it out by myself"?
this worked when I used an ofstream, and like I said it's a null-terminated string.
-
When you don't want to use the format of QDataStream then use ofstream or something else. The format of QDataStream is fixed and can not be changed. The output of a QDataStream is also only to be used with QDataStream and nothing else. So either accept the 4 bytes or do it by your own / with another class.