gpt4 book ai didi

c++ - 二进制文件流到字节 std::vector 跳过空格

转载 作者:行者123 更新时间:2023-11-28 05:45:24 24 4
gpt4 key购买 nike

当我使用这段代码时

std::string filename = "tmp.bin";
std::ifstream fileStream;
std::vector<unsigned char> fileBuffer;

fileStream = std::ifstream(filename.c_str(), std::ios::binary | std::ios::ate);
fileBuffer.reserve(fileStream.tellg());
fileStream.seekg(0, std::ios::beg);
fileBuffer.insert(fileBuffer.begin(), std::istream_iterator<BYTE>(fileStream), std::istream_iterator<BYTE>());

我的二进制文件中的所有原始空格都被跳过 -> fileBuffer 不包含空格,但需要 Base64 编码的所有标记。

这里有什么问题吗?

最佳答案

您需要使用 std::istreambuf_iterator<char> , istream_iterator使用 operator>>提取数据,用于 charunsigned char默认情况下将跳过空格。

旁注:C++ 中的 filebufs 是根据 C 标准定义的,在关于查找二进制文件末尾的注释中有以下说明:

Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream (because of possible trailing null characters) or for any stream with state-dependent encoding that does not assuredly end in the initial shift state.

无论如何它都可能工作正常,但除非重新分配是一个严重的问题,否则您应该一次性处理文件

std::ifstream fileStream("tmp.bin", std::ios::binary);
std::vector<char> fileBuffer{
std::istreambuf_iterator<char>(fileStream),
std::istreambuf_iterator<char>()
};

较旧的 C++ 需要避免使用

进行令人烦恼的解析
std::vector<char> fileBuffer(
(std::istreambuf_iterator<char>(fileStream)),
std::istreambuf_iterator<char>()
);

如果您的图书馆有 char_traits对于 unsigned char你也可以使用 std::basic_ifstream<unsigned char>虽然这不是可移植的,但您始终可以转换为 unsigned char无论如何,稍后取决于您的需要。

关于c++ - 二进制文件流到字节 std::vector 跳过空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36326081/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com