给定一个包含以下十六进制代码的文件:0B 00 00 00 00 00 20 41
我正在尝试填充std::vector <:uint8_t>然后手动检查每个字节。
这是我使用迭代器构造函数从两个 std::istream_iterators 创建向量的代码
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 向量转换为无符号字符?
istream_iterator
不应该用于读取二进制文件。它用operator>>
,它也不适合读取二进制文件(除非这些文件具有非常特定的格式,大多数二进制文件都不适合)。您可以使用istreambuf_iterator反而。您还需要确保以二进制模式打开文件。
in.open("filepath", std::ios::in | std::ios::binary);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)