[Interest] reading from and writing to a file with QDataStream

william.crocker at analog.com william.crocker at analog.com
Mon Mar 7 14:51:51 CET 2016


>
> int main()
> {
> // module A creates a byte array
> QByteArray bai;
> QDataStream out(&bai, QIODevice::WriteOnly);
> out << QString("A QString"); // writes some information on it
>

Some tool kits use a buffer in their version of QDataStream.
You can not in general be sure that anything has actually been
written to 'bai' here because 'out' is still alive.

> // passing bai to module A
> // module A do something...
>
> 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;
>
> // 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

You are reading an 'int' but you did not insure that an 'int' was written.
Year wrote a QByteArray, but are then reading a 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?
>
> Thank you,
> Sina
>
>
>
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> http://lists.qt-project.org/mailman/listinfo/interest



More information about the Interest mailing list