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
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
每一项被写入的数据,都是按一种预定义的二进制格式写入的,改格式取决于具体每