| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 799 人关注过本帖
标题:Qt读写二进制文件出错
只看楼主 加入收藏
songhuirong1
Rank: 2
等 级:论坛游民
帖 子:116
专家分:38
注 册:2010-6-15
结帖率:94.12%
收藏
 问题点数:0 回复次数:1 
Qt读写二进制文件出错
最近我写了一段读写二进制文件的代码,结果程序运行出错了。麻烦各位大大帮忙看看。谢谢了!
代码如下“
程序代码:
#include <QtGui/QApplication>
#include <QFile>
#include <QtDebug>

class Data
{
    friend void writeToFile(const QString &);
    friend void readFromFile(const QString &);
public:
    Data() {}
    Data(quint16 id, const QString &name)
    {
        this->id = id;
        this->name = name;
    }
private:
    quint16 id;
    QString name;
};

void writeToFile(const QString &filename)
{
    QFile file(filename);

    if(!file.open(QIODevice::WriteOnly))
    {
        qDebug() << "Can not open file" << filename;

        return;
    }

    QDataStream out(&file);
    out.setVersion(QDataStream::Qt_4_7);

    quint32 magicNumber = quint32(0xBE14CF47);
    QString names[10] = {"sunsong","jackwu","luckydai","karyyi","jackxu",
                         "skiffyuan","stanleyyan","fengminhe","junluo","yutaozhang"};

    out.writeRawData((char *)&magicNumber, (int)sizeof(quint32));

    for(int i = 0; i < 10; ++i)
    {
        Data data(quint16(i), names[i]);
        qDebug() << "Write id:" << quint16(i);
        qDebug() << "Write name:" << names[i];
        out.writeRawData((char *)&data, (int)sizeof(Data));
    }
}

void readFromFile(const QString &filename)
{
    QFile file(filename);

    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "Can not open file" << filename;

        return;
    }

    QDataStream in(&file);
    in.setVersion(QDataStream::Qt_4_7);

    quint32 magicNumber;

    in.readRawData((char *)&magicNumber, (int)sizeof(quint32));

    if(magicNumber != 0xBE14CF47)
    {
        qDebug() << "File not support!";

        return;
    }

    for(int i = 0; i < 10; ++i)
    {
        Data data;
        in.readRawData((char *)&data, (int)sizeof(Data));
        quint16 id = data.id;
        qDebug() << "Read id:" << id;
        QString name = data.name;
        qDebug() << "Read name:" << name;
    }
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    const QString filename("g:/temp/qtio.dat");
    writeToFile(filename);
    readFromFile(filename);

    return a.exec();
}
但是运行后挂掉了。不知道为何。
搜索更多相关主题的帖子: void private include public 
2012-04-15 10:34
songhuirong1
Rank: 2
等 级:论坛游民
帖 子:116
专家分:38
注 册:2010-6-15
收藏
得分:0 
这Qt版块怎么如此不活跃呢。。。。。。。。。。。。
2012-04-16 21:56
快速回复:Qt读写二进制文件出错
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.043028 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved