简体   繁体   English

C++ 将字节写入文件

[英]C++ writing byte to file

I am trying to write one byte to a file in C++.我正在尝试将一个字节写入 C++ 中的文件。 When I save it, is is 8 byte large, instead of 1 byte.当我保存它时,它是 8 字节大,而不是 1 字节。 How can I save exactly one byte?我怎样才能准确地保存一个字节?

ofstream binFile("compressed.bin", ios::out | ios::binary);
bitset<8> a("10010010");
binFile << a;

Output of ls -la: ls -la 的 Output:

.rw-r--r-- name staff   8 B  Sat Dec  4 23:26:18 2021  compressed.bin

How can I small it down to one byte?我怎样才能把它缩小到一个字节?

operator << is designed for formatted output. operator <<专为格式化的output 设计。

When writing strict binary, you should focus on member functions put (for one byte) or write (for variable number of bytes).在编写严格的二进制文件时,您应该关注成员函数put (用于一个字节)或write (用于可变字节数)。

This will write your bitset as a single byte.这会将您的位集写入单个字节。

binFile.put( a.to_ulong() );

I'm not sure what class bitset<size_t> is, but it seems to be creating a uint64_t underneath.我不确定 class bitset<size_t> 是什么,但它似乎在下面创建了一个 uint64_t 。 Maybe the template parameter is for number of bytes instead of bits?也许模板参数是字节数而不是位?

I can achieve a single byte binary file with我可以用

std::ofstream binFile("onebyte.bin", std::ios::out | std::ios::binary);
uint8_t aByte = 0x77; // this is w in ASCII. Easy to see in a bin file
binFile << aByte;

Perhaps you need to cast bitset to a uint8_t?也许您需要将 bitset 转换为 uint8_t?

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

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