-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrecover.c
74 lines (68 loc) · 1.85 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#define BLOCK_SIZE 512
#define FILENAME_MEM 8
bool is_jpg_header(uint8_t read[BLOCK_SIZE]);
int main(int argc, char *argv[])
{
// Check for proper command line arguemnts
if (argc != 2)
{
printf("Usage: ./recover image");
return 1;
}
FILE *input = fopen(argv[1], "r");
if (input == NULL)
{
printf("Could not open file.\n");
return 2;
}
uint8_t buffer[BLOCK_SIZE];
bool first_jpg = true;
char filename[FILENAME_MEM];
int count = 0;
FILE *output = NULL;
// Iterate through all the blocks until the end of file
while (fread(buffer, BLOCK_SIZE, 1, input))
{
// If valid header, start writing jpg
if (is_jpg_header(buffer))
{
if (first_jpg)
{
first_jpg = false;
}
// If not first jpg close previous write file
else
{
fclose(output);
}
// Update filename accoring to count
sprintf(filename, "%03i.jpg", count++);
// Open filename in write mode
output = fopen(filename, "w");
if (output == NULL)
{
return 3;
}
// Start writing to filenmae.jpg
fwrite(buffer, BLOCK_SIZE, 1, output);
}
// If not valid header and not first jpeg continue writing to previous jpeg
else if (!first_jpg)
{
fwrite(buffer, BLOCK_SIZE, 1, output);
}
}
fclose(output);
}
// Returns true if and only if we have specified JPEG header
bool is_jpeg_header(unsigned char header[])
{
return (header[0] == SOI_0 &&
header[1] == SOI_1 &&
header[2] == APPN &&
((header[3] & 0xf0) == 0xe0));
}