Why can#39;t I read fstream#39;s binary data with operatorgt;gt;?(为什么我不能用 operatorgt;gt; 读取 fstream 的二进制数据?)
问题描述
如果我执行以下操作:
ifstream file;
file.open("somefile", ios::binary);
unsigned int data;
file >> data;
我的流将始终设置 failbit 并且 data 将保持未初始化状态.但是,如果我改为读取 char 或 unsigned char ,则流很好.perror() 告诉我结果太大".
My stream will always set the failbit and the data will remain uninitialized. However, if I read a char or unsigned char instead, the stream is fine. perror() is telling me "result too large".
我在 Google 上看到的唯一内容是一个建议说 operator>> 不应该用于二进制数据(更喜欢 read()),但我发现操作符更干净、更易于使用——而且它不需要强制转换所有内容.
The only thing I saw on Google was a suggestion saying that operator>> shouldn't be used for binary data (prefer read()), but I find the operator to be cleaner and easier to use -- and it doesn't require casting everything.
谁能解释一下这个问题?
Can someone explain this issue?
推荐答案
iostream 提取运算符 (>>) 尝试解释由空格分隔的数字字符串,而不是二进制数据.有许多不同的方法可以对二进制形式的无符号整数进行编码(例如,32 位 2 的补码表示 在 小端字节序).这就是为什么你必须使用 read/write 函数对此类二进制缓冲区进行操作.
The iostream extraction operator (>>) attempts to interpret numerical strings separated by whitespace, not binary data. There are many different ways to encode an unsigned integer in binary form (e.g. a 32-bit 2's complement representation in little-endian byte order). That's why you must use the read/write functions to operate on such binary buffers.
但是,没有什么能阻止您实现自己的类,以便使用插入和提取运算符以您希望的任何形式序列化二进制数据.这样的类可能会在内部使用 ifstream 对象的读取函数.或者,boost 序列化库可能已经持有正是你想要的.
However, nothing prevents you from implementing your own class for serializing binary data in whatever form you wish using the insertion and extraction operators. Such a class would likely use the read function of an ifstream object internally. Alternatively, the boost serialization library may already hold exactly what you want.
这篇关于为什么我不能用 operator>> 读取 fstream 的二进制数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能用 operator>> 读取 fstream 的二进制数据?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
