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;
- int jpgcnt = 0;
- char jpgname[7];
- FILE *img;
- // actual images recovering
- while (true)
- {
- //write next 512 bytes of inptf to buffer
- fread(buffer, sizeof(int) * 512, 1, inptf);
- //go back 512 bytes and check them one more time with fseek to find if this 'box' is last in file
- fseek(inptf, -512, SEEK_CUR);
- x = fread(buffer, 1, 512, inptf);
- if (x == 512)
- {
- //check if it is beggining of the jpg
- 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);
- }
- }
- // if last "box" of file, write bytes to output file, then break the loop
- else if (jpgcnt > 0)
- {
- fwrite(buffer, 512, 1, img);
- fclose(img);
- break;
- }
- }
- // close infile at the and of the program
- fclose(inptf);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement