QDataStream无法序列化数据

编程入门 行业动态 更新时间:2024-10-10 23:25:23
本文介绍了QDataStream无法序列化数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试按照教程此处进行操作并序列化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无法序列化数据

本文发布于:2023-11-12 13:09:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581592.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列化   数据   QDataStream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!