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

标签 c++ c++11 vector hex istream-iterator

给定一个包含以下十六进制代码的文件: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/

相关文章:

c++ - 使用 'this' 关键字从 vector 中删除元素

c++ - 该 vector 按哪个值排序?

c++ - 为什么没有用户提供 cp/mv ctor 且具有虚拟函数但没有虚拟基的类没有 "trival cp/mv ctor"?

c++ - 如何检索 vector 中第一个找到的具有最低值的元素

c++ - 对对象映射进行排序 C++

C++/错误“没有匹配的调用函数

c++ - 在 Linux 中,recv() 有效但 recvmsg() 无效

c++ - 计算返回零而不是预期结果

c++ - std::initializer_list 替代方案

c++ - 迭代基本类型时使用 const 引用有什么缺点吗?