无法将二进制文件读入std :: vector 在C ++中[重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

我试图将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<unsigned char>,它可以正常工作。

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

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


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

编辑:

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

c++ io byte c++17 binaryfiles
1个回答
3
投票

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);
© www.soinside.com 2019 - 2024. All rights reserved.