温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - How to write byte(s) to a file in C++?
bit byte c++ file-handling huffman-code

其他 - 如何在C ++中将字节写入文件?

发布于 2020-05-06 11:46:29

我创建了一个std::bitset<8> bits等于000000001个字节的位集。我已将输出文件定义为,std::ofstream outfile("./compressed", std::ofstream::out | std::ofstream::binary)但是当我编写bitsusing时outfile << bits,的内容outfile变为00000000 但文件的大小为8个字节。(最后的每一位bits占用文件中的1个字节)有什么办法可以将字节真正写入文件吗?例如,如果我写,11010001则应将其写为一个字节,并且文件大小应为1字节而不是8字节。我正在为霍夫曼编码器编写代码,但无法找到将编码后的字节写入输出压缩文件的方法。

查看更多

提问者
Abhinav
被浏览
9
Travis Gockel 2020-02-18 02:32

问题是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
    }
}