我正在尝试按照教程此处进行操作并序列化Qt对象.这是我的代码:
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;运行该程序时,可以在桌面上创建文件,但是文件大小为0 kB,为空白.自然,当我再尝试以下方法时:
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;我在str中得到一个空白字符串.我究竟做错了什么?如果有帮助,我正在使用基于Qt 5.2.1的Qt Creator 3.1.1.
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.
推荐答案检查调用open时是否返回任何错误,并确保在完成操作后使用file.close()关闭该文件.
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.
在使用Qt 5时,您应该真正使用 QSaveFile 而是在保存数据时.
As you're using Qt 5, you should really use QSaveFile instead, when saving the data.
更多推荐
QDataStream无法序列化数据
发布评论