Advertisement
rupek1995

Untitled

Mar 1st, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4.  
  5. typedef uint8_t  BYTE;
  6.  
  7. int check_header_is_jpeg();
  8.  
  9. int main(int argc, char *argv[])
  10. {
  11.     // check proper usage
  12.     if (argc != 2)
  13.     {
  14.         fprintf(stderr, "usage: ./recover filename\n");
  15.         return 1;
  16.     }
  17.  
  18.     // keep filenames
  19.     char *infile = argv[1];
  20.     char *outfile = "000.jpg";
  21.     FILE *inptr = fopen(infile, "r");
  22.     FILE *outptr = fopen(outfile, "w");
  23.  
  24.     // check if files open properly
  25.     if (inptr == NULL)
  26.     {
  27.         fprintf(stderr, "Could not open %s\n", infile);
  28.         return 2;
  29.     }
  30.     if (outptr == NULL)
  31.     {
  32.         fprintf(stderr, "Could not write in %s\n", infile);
  33.         return 3;
  34.     }
  35.     while (!check_header_is_jpeg(inptr))
  36.     {
  37.         fseek(inptr, 512, SEEK_CUR);
  38.     }
  39.  
  40.     // only keep reading if block is proper size (512)
  41.     while (fread(outptr, 1, 512, inptr) == 512)
  42.     {
  43.         check_header_is_jpeg(inptr);
  44.         fwrite(&outptr, 512, 1, inptr);
  45.     }
  46.  
  47.     printf("end\n");
  48.  
  49.     // close files
  50.     fclose(inptr);
  51.     fclose(outptr);
  52.     return 0;
  53. }
  54.  
  55.  
  56. int check_header_is_jpeg(FILE *memcard)
  57. {
  58.     BYTE *BLOCKHEADER = malloc(4 * sizeof(BYTE));
  59.     // read first 4 bytes of current memory block
  60.     for (int i = 0; i < 4; i++)
  61.     {
  62.         fread(&BLOCKHEADER[i], 1, 1, memcard);
  63.     }
  64.  
  65.     // rewind seek back to beginning of block
  66.     fseek(memcard, -4, SEEK_CUR);
  67.  
  68.     // check if header is the same as JPEG header, return true if it is
  69.     if (BLOCKHEADER[0] == 0xff &&
  70.         BLOCKHEADER[1] == 0xd8 &&
  71.         BLOCKHEADER[2] == 0xff &&
  72.         (BLOCKHEADER[3] & 0xf0) == 0xe0)
  73.     {
  74.         printf("JPEG Header found!\n");
  75.         free(BLOCKHEADER);
  76.         return 1;
  77.     }
  78.     else
  79.     {
  80.         free(BLOCKHEADER);
  81.         return 0;
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement