[Interest] reading from and writing to a file with QDataStream
Thiago Macieira
thiago.macieira at intel.com
Mon Mar 7 18:33:01 CET 2016
Em segunda-feira, 7 de março de 2016, às 15:41:49 PST, Sina Dogru escreveu:
> int main()
> {
> // module A creates a byte array
> QByteArray bai;
> QDataStream out(&bai, QIODevice::WriteOnly);
> out << QString("A QString"); // writes some information on it
>
> // passing bai to module A
> // module A do something...
The problem is here. You've removed the bug from the sample source. So we
can't help you.
Most likely module A is overwriting the byte array, instead of appending to
it.
> QFile file("file.dat");
> file.open(QIODevice::WriteOnly);
>
> QDataStream out2(&file); // and module A write those datas to a file.
> out2 << bai.size();
> out2 << bai;
Did you really mean to write a datastream that contains a datastream inside?
Did you mean to nest one inside the other?
> // and module B starts
> if (file.isOpen())
> file.close();
>
> file.open(QIODevice::ReadOnly);
> QDataStream in(&file);
>
> QString str;
> int a; // extracts size information
> in >> a >> str; // extracts QString
> file.close();
>
> qDebug() << str << a; // output: "\u0000\u0012A QString" 22
> return 0;
> }
>
> I guess using QByteArray get things messed up. But then is there any advice
> to pass the information to another function?
You nested one datastream inside the other. You should match the encoding
steps when decoding and you didn't do that.
You should read the size, then extract a QByteArray, then use that as the data
for another QDataStream and then read a QString.
The difference is an extra length argument marshalled in the stream.
--
Thiago Macieira - thiago.macieira (AT) intel.com
Software Architect - Intel Open Source Technology Center
More information about the Interest
mailing list