如何读取用std::ifstream编写的QDataStream二进制文件

How to read a binary file that was written with QDataStream with std::ifstream

本文关键字:ifstream 二进制文件 QDataStream std 何读取 读取      更新时间:2023-10-16

我想读取一个用QDataStream编写并用std::fstream在LittleEndian中编码的二进制文件(在同一平台上,因此一种数据类型具有不同格式的问题不值得关注)。

我该如何最好地做到这一点?据我所知,std::fstream没有读取/写入LittleEndian数据的内置功能。

我深入研究了这个问题,发现了以下(伪代码):

ofstream out;      //initialized to file1, ready to read/write
ifstream in;       //initialized to file2; ready to read/write
QDataStream q_out; //initialized to file2; ready to read/write
int a=5, b;
//write to file1
out << a; //stored as 0x 35 00 00 00. Curiously, 0x35 is the character '5' in ASCII-code
//write to file2
q_out << a; //stored as 0x 05 00 00 00
//read from file2 the value that was written by q_out
in >> b; //will NOT give the correct result
//read as raw data
char *c = new char[4];
in.read(c, 4);
unsigned char *dst = (unsigned char *)&b;
dst[3] = c[3];
dst[2] = c[2];
dst[1] = c[1];
dst[0] = c[0];
//b==5 now

综上所述:QDataStream以与std::fstream不同的格式写入二进制数据。有没有一种简单的方法可以使用std::fstream读取QDataStream编写的二进制数据?

假设您在Little Endian机器上,这很可能,然后读取包含以下int的文件:

05 00 00 00

就像一样直接

int32_t x;
in.read((char*)&x, sizeof(int32_t));
assert(x == 5);

更多注意事项:

  • 运算符>><<执行格式化的i/o,也就是说,它们将值转换为文本表示形式,这与您的情况无关
  • 您应该以二进制模式(ios_base::binary标志)打开文件。POSIX不区分二进制和文本,但其他一些操作系统可以区分