QDataStream unable to serialize data

可紊 提交于 2019-12-25 04:10:53

问题


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.


回答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.



来源:https://stackoverflow.com/questions/27045488/qdatastream-unable-to-serialize-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!