-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecover.c
57 lines (52 loc) · 1.33 KB
/
recover.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <cs50.h>
typedef uint8_t BYTE;
#define BLOCK_SIZE 512
#define FILE_NAME_SIZE 8
bool is_start_new_jpg(BYTE buffer[]);
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
FILE* infile = fopen(argv[1], "r");
if (infile == NULL)
{
printf("File not found\n");
return 1;
}
BYTE buffer[BLOCK_SIZE];
int file_index = 0;
bool have_find_first_jpg = false;
FILE* outfile;
while (fread(buffer, BLOCK_SIZE, 1, infile))
{
if(is_start_new_jpg(buffer))
{
if(!have_find_first_jpg)
have_find_first_jpg = true;
else
fclose(outfile);
char filename[FILE_NAME_SIZE];
sprintf(filename, "%03i.jpg", file_index++);
outfile = fopen(filename, "w");
if (outfile == NULL)
return 1;
fwrite(buffer, BLOCK_SIZE, 1, outfile);
}
else if (have_find_first_jpg)
{
fwrite(buffer, BLOCK_SIZE, 1, outfile);
}
}
fclose(outfile);
fclose(infile);
}
bool is_start_new_jpg(BYTE buffer[])
{
return buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0;
}