0

I am trying to follow the tutorial here and serialize Qt objects. Here is my code:

QFile file("/Users/kaustav/Desktop/boo.dat");
if (!file.open(QIODevice::WriteOnly)) {
    qDebug() << "Cannot open file for writing: "
         << qPrintable(file.errorString()) << endl; //no error message gets printed
    return 0;
}
QDataStream out(&file);   // we will serialize the data into the file
out.setVersion(QDataStream::Qt_5_3); //adding this makes no difference
out << QString("the answer is");   // serialize a string
out << (qint32)42;

When I run this program, the file gets created in my desktop all right, but its size is 0 kB, it is blank. Naturally, when I then try this:

 QFile file("/Users/kaustav/Desktop/boo.dat");
 file.open(QIODevice::ReadOnly);
 QDataStream in(&file);    // read the data serialized from the file
 in.setVersion(QDataStream::Qt_5_3);
 QString str;
 qint32 w;
 in >> str >> w;

I get a blank string in str. What am I doing wrong? If of any help, I am using Qt Creator 3.1.1 based on Qt 5.2.1.

SexyBeast
  • 7,913
  • 28
  • 108
  • 196

1 Answers1

1

Check if there are any errors returned when calling open and ensure you close the file with file.close() when you're finished with it.

As you're using Qt 5, you should really use QSaveFile instead, when saving the data.

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85
  • Voila, adding `close()` works! But why do I need that! In C++, file handles get closed automatically when the variable goes out of close, isn't it? – SexyBeast Nov 20 '14 at 17:34
  • Looking at the Qt source code for QFile, it does call close, which does flush the stream. It may be that QDataStream is being deleted before it has time to complete streaming to the file. – TheDarkKnight Nov 21 '14 at 08:59
  • Yes, that is possible. Thanks, any way! :) – SexyBeast Nov 21 '14 at 09:34