Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Recovers lost jpegs from memory card
- */
- #include <cs50.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <stdint.h>
- typedef uint8_t BYTE;
- int main (int argc, char *argv[])
- {
- //check for correct no. of CLA
- if (argc != 2)
- {
- fprintf(stderr, "correct usage: one CLA with name of file to recover\n");
- return 1;
- }
- //open file for reading
- FILE *infile = fopen(argv[1], "r");
- //check that file to recover is not null
- if (infile == NULL)
- {
- fprintf(stderr, "Could not open %s.\n", argv[1]);
- return 2;
- }
- //open array for storing title
- char *title = malloc(8 * sizeof(char));
- //open buffer
- BYTE buffer[512];
- int number = 0;
- do
- {
- //start of jpeg found
- if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
- {
- //name new jpeg file
- sprintf(title, "%03i.jpg", number);
- //open outfile for writing
- FILE *outfile = fopen(title, "w");
- //check that outfile opens successfully
- if (outfile == NULL)
- {
- fprintf(stderr, "could not open %s.\n", title);
- return 3;
- }
- //write 512 bytes to outfile
- fwrite(&buffer, 1, 512, outfile);
- //increase number
- number++;
- }
- else //not start of jpeg
- {
- //if jpeg already found
- if (number > 0)
- {//not start of jpeg
- //append to already open jpg
- FILE *outfile = fopen(title, "a");
- fwrite(&buffer, 1, 512, outfile);
- }
- }
- }
- while (fread(&buffer, 1, 512, infile) == 512);
- // close infile
- fclose(infile);
- //free title
- free(title);
- // success
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement