title: Write a JPG image file in C
body: <p>I read JPEG image file and store its bits to a text file. Now I wanna convert back to valid JPEG image using those bits in the text file. I have tried writing a binary file but it doesn't retrieve the image file.</p>
  
  <p>Please steer me to the right direction. I'm busting my head into this for couple of days but no luck so far.</p>
  
  <p>Here is my code for writing JPG file:</p>
  
  <pre><code>int length;
  unsigned char *inData;  
  char Buffer[9];
  int c = 0, x;
  /* file.txt has single bit per line. */
  FILE *reader = fopen(file.txt, "r"); 
  FILE *writer = fopen("output.JPG","wb");
  
  fseek(reader, 0, SEEK_END);
  length=ftell(reader);
  fseek(reader, 0, SEEK_SET);
  
  for(x=0; x &lt; length; x++){
      fscanf(reader, "%d", &amp;inData);
      if(c &lt;= 8){       /*  reading 8-bits  */
          Buffer[c] = inData;
      } else {
          fwrite(&amp;Buffer, sizeof(Buffer), 1, writer);
          c = 0;
      }
      c++;
  }
  
  fclose(reader);
  fclose(writer);
  </code></pre>
  
  <p>Here is the code snippet for reading input.JPG and writing its bits to file.txt</p>
  
  <pre><code>    char *buffer;
  int fileLen;
  FILE *file = fopen("inputIM.JPG", "rb");
  
  fseek(file, 0, SEEK_END);
  fileLen=ftell(file);
  fseek(file, 0, SEEK_SET);
  
  buffer=(char *)malloc(fileLen+1);
  fread(buffer, fileLen, 1, file);
  fclose(file);
  convertToBit(&amp;buffer, fileLen);
  free(buffer);
  }
  
  // convert buffer data to bits and write them to a text file   
  convertToBit(void *buffer, int length)
  {
  int c=0;
  int SIZE = length * 8;
  unsigned char bits[SIZE + 1];
  unsigned char mask = 1;
  unsigned char byte ;
  int i = 0;
  FILE *bitWRT = fopen("file.txt", "w");
  
  for (c=0;c&lt;length;c++)
  {
      byte = ((char *)&amp;buffer)[c];
  
      for(i = 0; i &lt; 8; i++){
          bits[i] = (byte &gt;&gt; i) &amp; mask;
          fprintf(bitWRT, "%d\n", bits[i]);
      }
  }
  fclose(bitWRT);
  }
  </code></pre>
  
  <p>Thanks,</p>
  
  <p>-Sam</p>