title: C. CS50 recover assignment, recovering Jpg images
body: <p>I have a question about how to recover jpg images (it's an assignment for CS50).
  My code works for the most part (I believe), however I only get a bunch of thumbnails when I open the jpg's I found. </p>
  
  <p>I've been trying to solve this exercise for quite some time now but I can't seem to figure out why it doesn't work. Could somebody give me a push into the right direction.</p>
  
  <p>Here is my code (also available at <a href="http://pastebin.com/U2pwJd5e" rel="nofollow">http://pastebin.com/U2pwJd5e</a>):</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  #include "bmp.h"
  
  
  int main(int argc, char* argv[])
  {
  
      //get input file
      char* infile = "card.raw";
      // open card file
      FILE* inptr;
      inptr = fopen("card.raw", "r");
  
  
      // error checking (copied from copy.c)
      if (inptr == NULL)
      {
          printf("Could not open %s.\n", infile);
          return 2;
      }
  
      // initialize buffer
      BYTE buffer[512];
  
      //initialize jpg variables:
      int increment = 0;
      char outfilename[8];
  
      // while the end of the file is not reached, continue process &amp; write to buffer next block of 512 bytes
      while (fread(buffer, 512, 1, inptr) != 0)
      {
          // if the inpointer is not empty
          if(inptr != NULL)
          {
              // If the block of 512 bytes starts with markers
              if(buffer[0] == 0xff  &amp;&amp; buffer[1] == 0xd8  &amp;&amp; buffer[2] == 0xff &amp;&amp; (buffer[3]== 0xe1 || buffer[3]== 0xe0))
              {
                  // increase file number by 1
                  sprintf(outfilename,"%.3d.jpg", ++increment);
  
                  // open new file
                  FILE* outptr;
                  outptr = fopen(outfilename, "a");
  
                  // write first block of 512 bytes, then read next block
                  fwrite(buffer, 512, 1, outptr);
  
                  if(fread(buffer, 512, 1, inptr) == 0)
                         break;
  
                  // copy all information from inpointer to buffer to jpg
                  while((buffer[0] != 0xff  &amp;&amp; buffer[1] != 0xd8  &amp;&amp; buffer[2] != 0xff &amp;&amp; (buffer[3]!= 0xe1 || buffer[3]!= 0xe0) ))
                  {
                      // if next byte is NULL break
                      if(fread(buffer, 512, 1, inptr) == 0)
                          break;
  
                      fread(buffer, 512, 1, inptr);
  
                      //copies jpg file 1 byte at a time
                      fwrite(buffer, 512, 1, outptr);
  
                  }
  
                  // close file
                  fclose(outptr);
              }  
          }
  
      }
      return 0;
  }
  </code></pre>