gpt4 book ai didi

c++ - istream_iterator 遍历二进制文件中的字节

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:13 28 4
gpt4 key购买 nike

给定一个包含以下十六进制代码的文件:0B 00 00 00 00 00 20 41

我正在尝试填充一个 std::vector ,然后手动检查每个字节。

这是我使用迭代器构造函数从两个 std::istream_iterators 创建我的 vector 的代码

using Bytes   = std::vector<std::uint8_t>;
using ByteItr = std::istream_iterator<std::uint8_t>;

Bytes getBytes()
{
std::ifstream in;
in.open("filepath");
in.seekg(0, std::ios::beg);
Bytes bytes;
ByteItr start(in);
ByteItr end;
return Bytes(start, end);
}

这是我要让它通过的单元测试:

auto bytes = getBytes();

REQUIRE( bytes.size() == 8 );

CHECK( bytes[0] == 0x0B );
CHECK( bytes[1] == 0x00 );
CHECK( bytes[2] == 0x00 );
CHECK( bytes[3] == 0x00 );
CHECK( bytes[4] == 0x00 );
CHECK( bytes[5] == 0x00 );
CHECK( bytes[6] == 0x20 );
CHECK( bytes[7] == 0x41 );

为什么在这种情况下,它会跳过两个元素并将我的 std::uint8_t vector 隐式转换为无符号字符?

最佳答案

istream_iterator 不应用于读取二进制文件。它使用 operator>>,这也不适合读取二进制文件(除非这些文件是大多数二进制文件不适合的非常特殊的格式)。您可以使用 istreambuf_iterator反而。您还希望确保以二进制模式打开文件。

in.open("filepath", std::ios::in | std::ios::binary);

关于c++ - istream_iterator 遍历二进制文件中的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49424744/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com