-
Notifications
You must be signed in to change notification settings - Fork 412
/
Copy pathrecover.c
78 lines (62 loc) Β· 1.72 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
75
76
77
78
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#define BLOCK_SIZE 512
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "Usage: recover infile\n");
return 1;
}
// remember filenames
char *infile = argv[1];
// open input file
FILE *inptr = fopen(infile, "r");
if (inptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", infile);
return 2;
}
BYTE buffer[512];
int imageCount = 0;
char filename[8];
FILE *outptr = NULL;
while (true)
{
// read a block of the memory card image
size_t bytesRead = fread(buffer, sizeof(BYTE), BLOCK_SIZE, inptr);
// break out of the loop when we reach the end of the card image
if (bytesRead == 0 && feof(inptr))
{
break;
}
// check if we found a JPEG
bool containsJpegHeader = buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0;
// if we found a yet another JPEG, we must close the previous file
if (containsJpegHeader && outptr != NULL)
{
fclose(outptr);
imageCount++;
}
// if we found a JPEG, we need to open the file for writing
if (containsJpegHeader)
{
sprintf(filename, "%03i.jpg", imageCount);
outptr = fopen(filename, "w");
}
// write anytime we have an open file
if (outptr != NULL)
{
fwrite(buffer, sizeof(BYTE), bytesRead, outptr);
}
}
// close last jpeg file
fclose(outptr);
// close infile
fclose(inptr);
// success
return 0;
}