QDataStream 用法

// QDataStream是数据流,相当于数据管道,屏蔽了数据转换过程。
// 可以连接到一个设备上,这个设备可以是socket, file,或buffer
// 数据的表达方式,实际上是大端序,即大端在尾(大端在内存低地址).
// 更符合人们的阅读方式。
// QDataStream 支持QString 对象,丢弃了表达不太确切的buffer[xxxx]
//  对象的长度是可以知道的。 可以向QFile 输出数据看看,见例子程序
//  QProcess、QTcpSocket、QUdpSoctet 是顺序访问设备,它们的数据只能访问一遍,
//  也就是说,你只能从第一个字节开始访问,直到最后一个字节。
//  QFile、和 QBuffer 是随机访问设备,你可以从任何位置访问任意次数,
//  还可以使用 QIODevice::seek() 函数来重新定位文件指针。
#include <QtGui>
int main(int argc, char *argv[])
{
    (void)argc;
    (void)argv;

    int a=0x55aa;
    int b=0x12345678;
    QString str = "this is a string";
    int c,d;
    QFile file("test.dat");
    if(!file.open(QIODevice::WriteOnly))
    {
        printf("can't open file for write\n");
        exit(1);
    }
    QDataStream ds(&file);
    ds << a << b << str;
    file.close();

    if(!file.open(QIODevice::ReadOnly))
    {
        printf("can't open file for read\n");
        exit(1);
    }
    QDataStream ds2(&file);
    QString qstr;
    ds2 >> c >> d >> qstr;
    file.close();

    printf("a:%x, b:%x\n",a,b);
    printf("c:%x, d:%x, str:%s\n",c,d,qstr.toLatin1().data());

    return 0;

}$ hexdump -C test.dat
00000000  00 00 55 aa 12 34 56 78  00 00 00 20 00 74 00 68  |..U..4Vx... .t.h|
00000010  00 69 00 73 00 20 00 69  00 73 00 20 00 61 00 20  |.i.s. .i.s. .a. |
00000020  00 73 00 74 00 72 00 69  00 6e 00 67                      |.s.t.r.i.n.g|

由此可见,数据流在序列化数据时(输入或者输出),是按对象来操作的,对于QString 对象输入,它知道

首先取得0x20个长度, 后面是该QString 对象的数据。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值