Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputting bit data to binary file C++

I am writing a compression program, and need to write bit data to a binary file using c++. If anyone could advise on the write statement, or a website with advice, I would be very grateful.

Apologies if this is a simple or confusing question, I am struggling to find answers on web.

like image 968
Drew C Avatar asked Feb 01 '11 11:02

Drew C


People also ask

Does fwrite write in binary?

fread() and fwrite() functions are commonly used to read and write binary data to and from the file respectively.

How do you open a file for binary input output in C?

Use the fread Function to Read Binary File in C FILE* streams are retrieved by the fopen function, which takes the file path as the string constant and the mode to open them. The mode of the file specifies whether to open a file for reading, writing or appending.

What is the proper way of opening a file for writing as binary?

To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable.


1 Answers

Collect the bits into whole bytes, such as an unsigned char or std::bitset (where the bitset size is a multiple of CHAR_BIT), then write whole bytes at a time. Computers "deal with bits", but the available abstraction – especially for IO – is that you, as a programmer, deal with individual bytes. Bitwise manipulation can be used to toggle specific bits, but you're always handling byte-sized objects.

At the end of the output, if you don't have a whole byte, you'll need to decide how that should be stored. Both iostreams and stdio can write unformatted data using ostream::write and fwrite, respectively.

Instead of a single char or bitset<8> (8 being the most common value for CHAR_BIT), you might consider using a larger block size, such as an array of 4-32, or more, chars or the equivalent sized bitset.

like image 166
Fred Nurk Avatar answered Oct 17 '22 00:10

Fred Nurk