如何读取用std::ifstream编写的QDataStream二进制文件
How to read a binary file that was written with QDataStream with std::ifstream
我想读取一个用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不区分二进制和文本,但其他一些操作系统可以区分
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 当与Windows和Linux下的Ifstream相反的二进制文件时,结果不同
- ifstream读取二进制文件在发行模式下工作,但在调试模式下不使用
- 读取带有 ifstream 的二进制文件
- C++:使用std::ifstream读取二进制文件后删除缓冲区/指针时发生访问冲突
- 使用 ifstream 从C++文件中读取二进制无符号短整型
- 在二进制文件中从 ifstream 创建unique_ptr
- 使用 ifstream 剂量读取大型二进制文件不会填充字符缓冲区C++
- ifstream从二进制文件中读取的数据与预期不同
- 如何用ifstream和istreambuf_iterator读取二进制文件作为浮点数
- 如何读取用std::ifstream编写的QDataStream二进制文件