无法将二进制文件读取到 std::vector<std::byte> 中C++
Unable to read a binary file into std::vector<std::byte> in C++
我正在尝试阅读.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);
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- C 建造者Clang STD :: Sill,找不到超载的操作员&lt;
- 为什么STD :: MAP需要操作员&lt;以及我如何写一个
- std::vector::reserve(未知m),我知道m<<;N(通常)并且知道N
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- C++运算符<<调用::ostream而不是std::osttream
- 是std :: set&lt; std :: future&gt;不可能存在
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- C++重载<<具有typedef'd std::vector
- 以x的倍数填充前导零,使用std::cout<<std::十六进制
- 错误:没有匹配'运算符<<"在'std::cout
- std::pair的默认构造函数<>将基本类型(int等)设置为零
- std::ostream&operator< & lt; (std:: ostream&压力,压力& &;val)
- 将std::endl传递给std::operator<<
- std::映射<>或std::vector<>在处理大型标志集时
- 重载& lt; & lt;使用命名空间std