我为什么不能阅读的fstream的二进制数据与运营商的GT;&GT ;? [英] Why can't I read fstream's binary data with operator>>?

查看:253
本文介绍了我为什么不能阅读的fstream的二进制数据与运营商的GT;&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我做类似以下内容:

If I do something like the following:

ifstream的文件;
file.open(somefile,IOS ::二进制);

ifstream file; file.open("somefile", ios::binary);

无符号整型数据;

文件>>数据;

我流将始终旗故障位和数据将保持未初始化。但是,如果我读一个char或unsigned char相反,流是罚款。 PERROR告诉我造成太大。

my stream will always flag the fail bit and the data will remain unitialized. However, if I read a char or unsigned char instead, the stream is fine. perror is telling me "result too large".

我对谷歌看到的唯一的事情就是一个建议说,经营者应该>>不能用于二进制数据(preFER阅读()),但我觉得运营商更清洁和更容易使用 - 它不需要铸造一切。有人可以解释这个问题?

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 cleaner and easier to use -- and it doesn't require casting everything. Can someone explain the issue?

推荐答案

借助 iostream的提取运算符(>>)试图用空格隔开,而不是二进制数据间preT数字字符串。有许多不同的方式连接code二进制形式(一个无符号整数例如,一个32位 2的补重presentation 小尾数字节顺序)。这就是为什么你必须使用 /的功能,这样的二进制缓存操作。

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.

不过,从实现自己的类以任何形式祝你使用插入和提取运算符序列化的二进制数据没有prevents你。这样的类可能会使用一个ifstream的对象的读取功能在内部。另外,提振可能已经持有正是你想要的序列化库。

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.

这篇关于我为什么不能阅读的fstream的二进制数据与运营商的GT;&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆