Advertisement
Guest User

recover.c

a guest
Jun 24th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.89 KB | None | 0 0
  1. /*
  2. Recovers lost jpegs from memory card
  3. */
  4.  
  5. #include <cs50.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <stdint.h>
  10.  
  11. typedef uint8_t  BYTE;
  12.  
  13. int main (int argc, char *argv[])
  14. {
  15.     //check for correct no. of CLA
  16.     if (argc != 2)
  17.     {
  18.         fprintf(stderr, "correct usage: one CLA with name of file to recover\n");
  19.         return 1;
  20.     }
  21.  
  22.     //open file for reading
  23.     FILE *infile = fopen(argv[1], "r");
  24.     //check that file to recover is not null
  25.     if (infile == NULL)
  26.         {
  27.         fprintf(stderr, "Could not open %s.\n", argv[1]);
  28.         return 2;
  29.         }
  30.  
  31.     //open array for storing title
  32.      char *title = malloc(8 * sizeof(char));
  33.  
  34.     //open buffer
  35.     BYTE buffer[512];
  36.     int number = 0;
  37.  
  38.    do
  39.     {
  40.         //start of jpeg found
  41.         if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
  42.         {
  43.             //name new jpeg file
  44.             sprintf(title, "%03i.jpg", number);
  45.             //open outfile for writing
  46.             FILE *outfile = fopen(title, "w");
  47.             //check that outfile opens successfully
  48.             if (outfile == NULL)
  49.             {
  50.                 fprintf(stderr, "could not open %s.\n", title);
  51.                 return 3;
  52.             }
  53.             //write 512 bytes to outfile
  54.            fwrite(&buffer, 1, 512, outfile);
  55.             //increase number
  56.             number++;
  57.         }
  58.         else //not start of jpeg
  59.         {
  60.             //if jpeg already found
  61.         if (number > 0)
  62.         {//not start of jpeg
  63.         //append to already open jpg
  64.         FILE *outfile = fopen(title, "a");
  65.         fwrite(&buffer, 1, 512, outfile);
  66.         }
  67.         }
  68.     }
  69.     while (fread(&buffer, 1, 512, infile) == 512);
  70.      // close infile
  71.     fclose(infile);
  72.  
  73.     //free title
  74.     free(title);
  75.  
  76.     // success
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement