我正在努力学习教程 here并序列化 Qt 对象。这是我的代码:
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,它是空白的。自然地,当我尝试这个时:
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
。
最佳答案
检查调用打开时是否返回任何错误,并确保在完成后使用 file.close() 关闭文件。
当你使用 Qt 5 时,你真的应该使用 QSaveFile相反,在保存数据时。
关于c++ - QDataStream 无法序列化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27045488/