Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <cs50.h>
- int main (int argc, char* argv[])
- {
- //Check proper usage
- if (argc != 2)
- {
- fprintf(stderr, "Usage: ./recover infile\n");
- return 1;
- }
- // Remember infile name
- char *infile = argv[1];
- // create pointer in reading mode leading to infile
- FILE *inptf = fopen(infile, "r");
- //check if correct infile, not leading to NULL
- if (inptf == NULL)
- {
- fprintf(stderr, "Can't read infile\n");
- return 2;
- }
- // declare variables that will be used inside of loops
- int buffer[512];
- int x = 0;
- int jpgcnt = 0;
- char jpgname[7];
- FILE *img;
- // actual images recovering
- do
- {
- // read infile next 512 bytes to buffer
- fread(buffer, 512 * sizeof(int), 1, inptf);
- fseek(inptf, -512, SEEK_CUR);
- x = fread(buffer, 1, 512, inptf);
- if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
- {
- //if first encountered photo on card
- if (jpgcnt == 0)
- {
- //create new jpgfile name and open new file with this name
- sprintf(jpgname, "%03i.jpg", jpgcnt);
- img = fopen(jpgname, "w");
- if (img == NULL)
- {
- return 3;
- }
- //write chunk of photo to new file
- fwrite(buffer, 512, 1, img);
- jpgcnt++;
- }
- // when there were photos encountered on card before
- if(jpgcnt > 0)
- {
- //first close former image file, then create name for new one, open file with this name an write chunk of photo
- fclose(img);
- sprintf(jpgname, "%03i.jpg", jpgcnt);
- img = fopen(jpgname, "w");
- if (img == NULL)
- {
- return 3;
- }
- fwrite(buffer, 512, 1, img);
- jpgcnt++;
- }
- }
- //if we dont encounter new photo, and have one img file already opened, write other chunks of photo into it
- else if (jpgcnt > 0)
- {
- fwrite(buffer, 512, 1, img);
- }
- }
- // check if this was last 'box' in file
- while (x == 512);
- // write last bytes to output file, then close output file
- fwrite(buffer, 512, 1, img);
- fclose(img);
- // close infile at the and of the program
- fclose(inptf);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement