2

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?

scopchanov
  • 6,933
  • 10
  • 30
  • 56
uni
  • 397
  • 1
  • 6
  • 15
  • 1
    I like to include a checksum of the data and check its validity before even attempting to deserialize. Passing that check dramatically increases the chances of successful deserialization. Just don't use Qt's own checksum function, which is fairly mediocre with its 16 bit output. – dtech Oct 29 '18 at 11:56

1 Answers1

1

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.

Vladimir Bershov
  • 2,547
  • 1
  • 14
  • 42
  • Could you please provide more code that shows how it helps to find if there is an error in incoming data. For example if file.dat was garbage. – uni Oct 29 '18 at 11:28
  • Is it just: if (!in.commitTransaction()) { qDebug("eror"); } – uni Oct 29 '18 at 11:30
  • @uni , you have to check your data yourself. `QDataStream` is only responsible for the read operation itself if data available to read – Vladimir Bershov Oct 29 '18 at 11:34
  • What I meant is a way to check if incoming data at least can be extracted from datastream (An I will check it later). Your answer really helps. Thank you! Спасибо! – uni Oct 29 '18 at 11:42