从 C++ 中的二进制文件中读取 32 位整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32066027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read 32-bit integer from binary file in C++?
提问by plhn
My binary file looks like this.
我的二进制文件看起来像这样。
00000000: 0000 0803 0000 ea60 0000 001c 0000 001c
00000010: 0000 0000 0000 0000 0000 0000 0000 0000
left column is address.
左栏是地址。
I just tried to read 0000 0803
(=2051) as follows
我只是尝试阅读0000 0803
(= 2051)如下
ifstream if;
if.open("file");
uint32_t a;
if >> a;
As expected...It did not work :-( a
was just 0 after execution.
I tried long, int, unsigned int, unsigned long
. All failed.
正如预期的那样......它没有用 :-(a
执行后只是 0。
我试过了long, int, unsigned int, unsigned long
。一切都失败了。
Why these are not working and how can I achieve the goal?
为什么这些不起作用,我怎样才能实现目标?
回答by paulsm4
You have two issues:
你有两个问题:
Insuring you read the bytes you intend (no fewer, no more) from the stream.
I'd recommend this syntax:
uint32_t a;
inFILE.read(reinterpret_cast<char *>(&a), sizeof(a));
Insure you're interpreting those bytes with the correct byte order.
Q: If you're on a PC, your CPU is probably little endian. Do you know if your data stream is also little-endian, or is it big endian?
If the data is big-endian, I'd consider the standard networking functions to accomodate byte order:
ntohl()
, etc: http://www.retran.com/beej/htonsman.html
确保您从流中读取您想要的字节(不多也不少)。
我推荐这种语法:
uint32_t a;
inFILE.read(reinterpret_cast<char *>(&a), sizeof(a));
确保您使用正确的字节顺序解释这些字节。
问:如果您在 PC 上,您的 CPU 可能是小端。你知道你的数据流是小端还是大端?
如果数据是大端数据,我会考虑使用标准网络功能来适应字节顺序:
ntohl()
等:http: //www.retran.com/beej/htonsman.html
ALSO:
还:
Follow Hcorg's and Daniel Jour's advice: don't forget about the "open mode" parameter, and don't forget to check for "file open" errors.
遵循 Hcorg 和 Daniel Jour 的建议:不要忘记“打开模式”参数,不要忘记检查“文件打开”错误。
回答by VolAnd
Open file in binary mode and then use read()
method, something like:
以二进制模式打开文件,然后使用read()
方法,例如:
uint32_t a;
ifstream file ("file", ios::in | ios::binary);
if (file.is_open())
{
file.read ((char*)&a, sizeof(a));
}