Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * recover.c
- *
- * Computer Science 50
- * Problem Set 4
- *
- * Recovers JPEGs from a forensic image.
- */
- #include <cs50.h>
- #include <stdio.h>
- #include <stdint.h>
- #include <stdlib.h>
- typedef uint8_t BYTE;
- #define BLOCK 512;
- int main(int argc, char* argv[])
- {
- // TODO
- // open card.raw to read
- FILE* file = fopen("card.raw", "r");
- // check if file is NULL
- if (file == NULL)
- {
- printf("Could not open %s.\n", "card.raw");
- return 1;
- }
- // 512 byte block
- uint8_t block[512];
- int i = 0;
- int j = 0;
- FILE* img = NULL;
- // read from the file in a loop
- while (fread(block, sizeof(block), 1, file) == 1)
- {
- // if signature is found
- if (block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] == 0xe0 || block[3] == 0xe1))
- {
- // if this is the first jpg
- if (i == 0)
- {
- // malloc space for title of new jpgs
- char* title = malloc(sizeof(char));
- // print new title of jpgs
- sprintf(title, "%03d.jpg", i);
- // open newly titled jpg
- img = fopen(title, "w");
- if (img == NULL)
- {
- fclose(file);
- fprintf(stderr, "Could not create %s.\n", title);
- return 2;
- }
- fwrite(&block, sizeof(block), 1, img);
- // iterate i so program knows first jpg has been found
- i++;
- j++;
- free(title);
- }
- // if not first jpg
- else
- {
- // close previous jpg
- fclose(img);
- // increment 'i' (keeps track of jpgs)
- // my (not so elegant) solution on how to not pre-increment after first jpg
- if (j == 1)
- {
- j++;
- }
- else
- {
- i++;
- }
- // malloc space for title of new jpgs
- char* title = malloc(sizeof(char));
- // print new title of jpgs
- sprintf(title, "%03d.jpg", i);
- // open newly titled jpg
- img = fopen(title, "w");
- if (img == NULL)
- {
- fclose(file);
- fprintf(stderr, "Could not create %s.\n", title);
- return 2;
- }
- // write first block to new jpg
- fwrite(&block, sizeof(block), 1, img);
- free(title);
- }
- }
- // if new jpg signature not found, but i > 0 (meaning first jpg has already been hit)
- else if (i > 0)
- {
- fwrite(&block, sizeof(block), 1, img);
- }
- // if first jpg has not been found, do nothing
- else
- {
- i = i + 0;
- }
- }
- fclose(file);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement