简体   繁体   English

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

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

I have created a bitset using std::bitset<8> bits which is equivalent to 00000000 ie, 1 byte.我使用std::bitset<8> bits创建了一个std::bitset<8> bits ,它相当于00000000即 1 个字节。 I have output file defined as std::ofstream outfile("./compressed", std::ofstream::out | std::ofstream::binary) but when I write the bits using outfile << bits , the content of outfile becomes 00000000 but the size of file is 8 bytes.我已经输出文件定义std::ofstream outfile("./compressed", std::ofstream::out | std::ofstream::binary)但是当我写的bits使用outfile << bits ,内容outfile变为00000000但文件大小为 8 字节。 (each bit of bits end up taking 1 byte in the file) . (的每个比特bits最终以在文件中1个字节)。 Is there any way to truly write byte to a file?有没有办法真正将字节写入文件? For example if I write 11010001 then this should be written as a byte and the file size should be 1 byte not 8 bytes.例如,如果我写11010001那么这应该写为一个字节,文件大小应该是 1 个字节而不是 8 个字节。 I am writing a code for Huffman encoder and I am not able to find a way to write the encoded bytes to the output compressed file.我正在为霍夫曼编码器编写代码,但找不到将编码字节写入输出压缩文件的方法。

The issue is operator<< is the text encoding method, even if you've specified std::ofstream::binary .问题是operator<<是文本编码方法,即使您已指定std::ofstream::binary You can use put to write a single binary character or write to output multiple characters.您可以使用put写入单个二进制字符或write以输出多个字符。 Note that you are responsible for the conversion of data to its char representation.请注意,您负责将数据转换为其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