QDataStream 二进制数据读写

Qt中的QDataStream类为我们的程序提供了读写二进制数据的能力。一个数据流如果是二进制编码的数据流,那么它肯定是与计算机的操作系统、CPU或者字节序无关的。例如,一个数据流是在一个运行Windows系统的PC机上被写入的,那么它照样可以在一台运行Solaris的Sun SPARC的机器上被读取出来。同样,我们也可以使用QDataStream去读写原生的未编码的二进制数据。

QDataStream类实现了序列化C++的基本数据类型的功能,比如char,short,int,char* 等等。如果要序列化更复杂的数据类型,可以将复杂数据类型分解成独立的基本数据类型分别进行序列化。

一个数据流往往需要一个QIODevice配合使用。因为QIODevice代表了一个可以从中读取数据或向其写入数据的输入输出设备。我们最常常见的QFile文件类就是一种QIODevice。下面我们先分别看一个使用QDataStream进行二进制数据读写的例子。

write binary data to a stream:

  QFile file("file.dat");
  file.open(QIODevice::WriteOnly);
  QDataStream out(&file);   // we will serialize the data into the file
  out << QString("the answer is");   // serialize a string
  out << (qint32)42;        // serialize an integer


read binary data from a stream:

  QFile file("file.dat");
  file.open(QIODevice::ReadOnly);
  QDataStream in(&file);    // read the data serialized from the file
  QString str;
  qint32 a;
  in >> str >> a;           // extract "the answer is" and 42


每一项被写入的数据,都是按一种预定义的二进制格式写入的,改格式取决于具体每

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值