Home > Software design >  C writing byte to file
C writing byte to file

Time:12-05

I am trying to write one byte to a file in C . When I save it, is is 8 byte large, instead of 1 byte. 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:

.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?

CodePudding user response:

operator << is designed for formatted output.

When writing strict binary, you should focus on member functions put (for one byte) or write (for a variable number of bytes).

This will write your bitset as a single byte.

binFile.put( a.to_ulong() );

CodePudding user response:

I'm not sure what class bitset<size_t> is, but it seems to be creating a uint64_t underneath. 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?

  • Related