首页 > 解决方案 > 如何在 C++ 中将字节写入文件?

问题描述

我创建了一个位集,使用std::bitset<8> bits它相当于000000001 个字节。我将输出文件定义为,std::ofstream outfile("./compressed", std::ofstream::out | std::ofstream::binary)但是当我编写bitsusingoutfile << bits时,内容outfile变为00000000 但文件大小为 8 个字节。(每个位bits最终占用文件中的 1 个字节)。有没有办法真正将字节写入文件?例如,如果我写11010001,那么这应该写为一个字节,文件大小应该是 1 个字节而不是 8 个字节。我正在为 Huffman 编码器编写代码,但我无法找到将编码字节写入输出压缩文件的方法。

标签: c++bytebitfile-handlinghuffman-code

解决方案


问题是operator<<文本编码方法,即使您指定了std::ofstream::binary. 您可以使用put写入单个二进制字符或write输出多个字符。请注意,您负责将数据转换为其char表示形式。

std::bitset<8> bits = foo();
std::ofstream outfile("compressed", std::ofstream::out | std::ofstream::binary);

// In reality, your conversion code is probably more complicated than this
char repr = bits.to_ulong();

// Use scoped sentries to output with put/write
{
    std::ofstream::sentry sentry(outfile);
    if (sentry)
    {
        outfile.put(repr);                  // <- Option 1
        outfile.write(&repr, sizeof repr);  // <- Option 2
    }
}

推荐阅读