无法将二进制文件读取到 std::vector<std::byte> 中C++

Unable to read a binary file into std::vector<std::byte> in C++

本文关键字:std lt gt C++ byte vector 二进制文件 读取      更新时间:2023-10-16

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

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<unsigned char>它工作正常。

查看文档std::byte它看起来应该像一个unsigned char所以我不确定编译器在哪里感到困惑。

是否有任何特定的方式来将文件读取为字节向量?(我正在寻找一种现代C++方法(


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

编辑:

这个问题不是重复的,因为我特别关注现代C++技术和 std::byte 的使用,这个问题没有讨论。

std::byte是一个作用域枚举。 因此,对于转换为类型存在一些限制,而对于基本类型(如 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);