使用ifstream读取二进制数据

问题描述 投票:-2回答:2

可能,我对ifstream一无所知。我有二进制文件:0604 0204 0a02。

std::ifstream input(input_filename, std::ios::binary);
unsigned char cmd;
unsigned char type;
while (!input.eof()) {
    input >> cmd;
    input >> type;
    std::cout << static_cast<int>(cmd) << " " << (int)type << "\n";
}

此代码的结果:

6 4
2 4
2 0

出了什么问题?

c fstream
2个回答
0
投票

operator >>正在跳过空格。您需要呼叫operator >>input.read()


0
投票

cmd和type为字节类型,然后您将转换为int。尝试将类型更改为短整数[]

input >> std::noskipws >> cmd;
© www.soinside.com 2019 - 2024. All rights reserved.