title: Huffman Encoding, Saving codes and writing binary in C
body: <p>I have a problem with encoding a text file with Huffman.
  Let's say the line to encode is like the following:</p>
  
  <pre><code>AAAABBBCCAABBCCDFF
  </code></pre>
  
  <p>So the frequency table is like this :</p>
  
  <pre><code>A:6
  B:5
  C:4
  D:1
  F:2
  </code></pre>
  
  <p>So I build a tree, the struct is like this:</p>
  
  <pre><code>typedef struct node {
      struct node *left;
      struct node *right;
      unsigned char character;
      unsigned int flag; //needed for nodes with no value in Huffman-tree
      unsigned int occurences;
  } node; 
  </code></pre>
  
  <p>I know the codes should be:</p>
  
  <pre><code>A: 10
  B: 11
  C: 01
  D: 000
  F: 001
  </code></pre>
  
  <p>Now I want to get this codes from my tree, how can I do this easily?</p>
  
  <p>Secondly, I want to save those codes so I can easily look the codes up and write them to a binary file.</p>
  
  <p>How can I save those codes, and for writing, how can I write individual (or 2 or 3) bits to a binary file, because I know C wants bytes.</p>
  
  <p>I want to write it like this (codes sorted by byte and last byte is only 7 bits)</p>
  
  <pre><code>10101010 11111101 01101011 11010100 0001001 (only 7 bits)
  </code></pre>