繁体   English   中英

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

[英]How to write byte(s) to a file in C++?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM