Please, consider the following code fragment from the QDataStream
documentation:
QFile file("file.dat");
file.open(QIODevice::ReadOnly);
QDataStream in(&file); // read the data serialized from the file
QString str;
qint32 a;
in >> str >> a; // extract "the answer is" and 42
Is there a way to know that QDataStream
cannot deserialize the content of the file to QString
and qint32
and how to handle such deserialization errors in QDatastream
?
According to official documentation, you can (and should) use Read Transactions:
in.startTransaction();
QString str;
qint32 a;
in >> str >> a; // try to read packet atomically
if(in.commitTransaction())
{
// read is ok, check the data you had read
}
else
{
// wait for more data or show unknown error
}
If you have a file as an IO device, you can read without transactions, but you have to check manually whether the necessary amount of data is available. When using QDataStream you shall be sure about a sequence and composition of data.