c++ - QDataStream 无法序列化数据

标签 c++ qt persistence object-serialization qdatastream

我正在努力学习教程 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.1Qt Creator 3.1.1

最佳答案

检查调用打开时是否返回任何错误,并确保在完成后使用 file.close() 关闭文件。

当你使用 Qt 5 时,你真的应该使用 QSaveFile相反,在保存数据时。

关于c++ - QDataStream 无法序列化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27045488/

相关文章:

qt - QML - MouseArea - 传播 onPositionChanged

Redis故障备份模拟

java - 为什么 JPA 实体类及其方法不能声明为 final?

jpa - 如何在多个数据库(分布式系统)中保留相同的 JPA 实体?

c++ - C++中的循环继承

c++ - 是否有关于 std::move 的这种使用的编译警告?

c++ - MySQL Connector\C++ 中缺少示例目录(从哪里获取它们?)

现有协议(protocol)的 C++ 序列化库

c++ - QThread finished() 信号永远不会发出

qt - Qml QtQuick2 'Invalid property name "样式"(M16)'