Facebook
From Alex, 3 Years ago, written in C.
Embed
Download Paste or View Raw
Hits: 165
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <cs50.h>
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7.     //check command line arguments and make sure they are more than one
  8.     if (argc != 2)
  9.     {
  10.         printf("Usage: ./recover file\n");
  11.         return 1;
  12.     }
  13.    
  14.     FILE *inptr = fopen (argv[1], "r");
  15.     //if file does not exist return an error
  16.     if (inptr == NULL)
  17.     {
  18.         printf("Error! Could not recover\n");
  19.         return 2;
  20.     }
  21.     //create filename and buffer arrays
  22.     unsigned char buffer[512];
  23.     char filename[8];
  24.    
  25.     //set file count to 0
  26.     int jpeg_count = 0;
  27.     int picture = 0;
  28.     int found_jpeg = 0;
  29.    
  30.     //new file I'll be writing to
  31.     FILE* outptr = NULL;
  32.  
  33.         while (fread (buffer, sizeof(buffer), 1, inptr) == 1)
  34.         {
  35.             //find the beginning of jpg signature
  36.             if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
  37.             {
  38.                 //for first jpeg found
  39.               if (jpeg_count == 0)
  40.               {
  41.                   sprintf (filename, "%03i.jpg", jpeg_count);
  42.                   jpeg_count++;
  43.                  
  44.                   //open first file i.e. 000.jpg
  45.                   outptr = fopen (filename, "w");
  46.               }
  47.               //if jpeg already found
  48.               else
  49.               {
  50.                   //close current file that was being written to
  51.                   fclose(outptr);
  52.  
  53.                   sprintf (filename, "%03i.jpg", jpeg_count);
  54.                   jpeg_count++;
  55.                   //open new file just created to start writing data into it
  56.                   outptr = fopen (filename, "w");
  57.                   fwrite (buffer, sizeof(buffer), 1, outptr);
  58.               }
  59.             }
  60.            
  61.           if (outptr != NULL)
  62.               {
  63.                   //keep writing to current file if already in open jpeg
  64.                   fwrite (&buffer, sizeof(buffer), 1, outptr);
  65.               }
  66.         }
  67.         //close input file
  68.     fclose(inptr);
  69.    
  70.     //close output file
  71.     fclose(outptr);
  72.     return 0;
  73. }
  74.  
  75.