0

I'm working on a Huffman coding project, and I want to write individual bits of information to a file. Is there any way to do that in C? All the results I've looked up so far have just shown me how to print the characters '1' and '0' to a file, which is not what I want to do. To clarify, if I were to write '10100101' to a file, it should only take up one byte.

  • 2
    Pack the bits into bytes and write to a file in binary mode. – lurker Oct 10 '19 at 02:25
  • Possible duplicate of [How do you set, clear, and toggle a single bit?](https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit) – klutt Oct 10 '19 at 02:28
  • 1
    `'10100101'` is a string of the characters `'1'` and `'0'`to visually display individual bits in a byte. In order to write it as one byte, you'll need to convert it to an actual number, not a string, and write it in binary (not text) mode. That should give you enough information to do some searching and make an effort to solve the problem yourself. – Ken White Oct 10 '19 at 02:33

1 Answers1

1

The following code will write a byte with the binary value 10100101 (which is A5 in hexadecimal) to a file. It will be written in binary mode, i.e. not as a text string.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int main()
{
    FILE *fp;
    unsigned char to_write;
    size_t ret_val;

    fp = fopen( "testfile.bin", "wb" );
    assert( fp != NULL );

    to_write = 0xA5;

    ret_val = fwrite( &to_write, sizeof(to_write), 1, fp );
    assert( ret_val == 1 );

    fclose( fp );

    return 0;
}
Andreas Wenzel
  • 12,860
  • 3
  • 14
  • 29