title: How do I extract all the data from a bzip2 archive with C?
body: <p>I have a concatenated file made up of some number of <code>bzip2</code> archives. I also know the sizes of the individual <code>bzip2</code> chunks in that file. </p>
  
  <p>I would like to decompress a <code>bzip2</code> stream from an individual bzip2 data chunk, and write the output to standard output.</p>
  
  <p>First I use <code>fseek</code> to move the file cursor to the desired archive byte, and then read the "size"-chunk of the file into a <code>BZ2_bzRead</code> call:</p>
  
  <pre><code>int headerSize = 1234;
  int firstChunkSize = 123456;
  FILE *fp = fopen("pathToConcatenatedFile", "r+b");
  char *bzBuf = malloc(sizeof(char) * firstChunkSize);
  int bzError, bzNBuf;
  BZFILE *bzFp = BZ2_bzReadOpen(&amp;bzError, *fp, 0, 0, NULL, 0);
  
  # move cursor past header of known size, to the first bzip2 "chunk"
  fseek(*fp, headerSize, SEEK_SET); 
  
  while (bzError != BZ_STREAM_END) {
      # read the first chunk of known size, decompress it
      bzNBuf = BZ2_bzRead(&amp;bzError, bzFp, bzBuf, firstChunkSize);
      fprintf(stdout, bzBuf);
  }
  
  BZ2_bzReadClose(&amp;bzError, bzFp);
  free(bzBuf);
  fclose(fp);
  </code></pre>
  
  <p>The problem is that when I compare the output of the <code>fprintf</code> statement with output from running <code>bzip2</code> on the command line, I get two different answers. </p>
  
  <p>Specifically, I get less output from this code than from running <code>bzip2</code> on the command line. </p>
  
  <p>More specifically, my output from this code is a smaller subset of the output from the command line process, and I am missing what is in the tail-end of the bzip2 chunk of interest.</p>
  
  <p>I have verified through another technique that the command-line <code>bzip2</code> is providing the correct answer, and, therefore, some problem with my C code is causing output at the end of the chunk to go missing. I just don't know what that problem is.</p>
  
  <p>If you are familiar with <code>bzip2</code> or <code>libbzip2</code>, can you provide any advice on what I am doing wrong in the code sample above? Thank you for your advice.</p>