【问题标题】:Unable to read a binary file into std::vector<std::byte> in C++无法在 C++ 中将二进制文件读入 std::vector<std::byte>
【发布时间】:2019-04-20 21:03:59
【问题描述】:

我正在尝试将 C++ 中的 .WAV 文件读入二进制数据向量:

typedef std::istreambuf_iterator<char> file_iterator;

std::ifstream file(path, std::ios::in | std::ios::binary);
if (!file.is_open()) {
    throw std::runtime_error("Failed to open " + path);
}

std::vector<std::byte> content((file_iterator(file)), file_iterator());

当我尝试编译这段代码时,我得到一个错误:

无法在初始化中将 'char' 转换为 'std::byte'

但是,如果我将向量更改为 std::vector&lt;unsigned char&gt;,它就可以正常工作。

查看std::byte 的文档,它看起来应该像unsigned char 一样工作,所以我不确定编译器在哪里弄糊涂了。

有没有什么特别的方法可以将文件读入字节向量? (我正在寻找一种现代 C++ 方法)


我使用 MinGW 7.3.0 作为我的编译器。

编辑:

这个问题不是duplicate,因为我特别关心现代 C++ 技术和 std::byte 的使用,这在那个问题中没有讨论。

【问题讨论】:

  • std::istreambuf_iterator&lt;std::byte&gt; 无法编译。我一直在试图弄清楚为什么,但这似乎是意料之中的。

标签: c++ io byte c++17 binaryfiles


【解决方案1】:

std::byte 是一个作用域enum。因此,对于转换为 char 等基本类型不存在的类型存在限制。

由于std::byte 的基础类型是unsigned char,因此您无法在初始化期间将(签名的)char 转换为byte,因为该转换是一种缩小转换。

一种解决方案是使用unsigned char 的向量来存储文件内容。由于byte 不是算术类型,因此byte 不存在许多数字运算(仅按位运算)。

如果您必须使用std::byte,请使用该类型定义迭代器和fstream:

typedef std::istreambuf_iterator<std::byte> file_iterator;

std::basic_ifstream<std::byte> file(path, std::ios::in | std::ios::binary);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多