summaryrefslogtreecommitdiff
path: root/wk4/pset/recover/recover.c
blob: c10d032c85b9dd5f137ccc114ee81b2e84052b19 (plain)
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
#include <cs50.h>
#include <ctype.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./recover infile\n");
        return 1;
    }

    // Open input file
    FILE *card = fopen(argv[1], "r");
    if (card == NULL)
    {
        printf("Could not open %s.\n", argv[1]);
        return 1;
    }

    // initialize variables for use in restoring jpegs
    uint8_t buffer[512];
    int files = -1;
    char name[8];

    // restoring jpegs
    while (fread(buffer, 1, 512, card) == 512)
    {
        // check if this is a new picture
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && buffer[3] >= 0xe0 &&
            buffer[3] <= 0xef)
        {
            // this is a jpeg, make a new file from it
            files++;
            sprintf(name, "%i%i%i.jpg", files / 100, (files / 10) % 10, files % 10);
            FILE *point = fopen(name, "w");
            fwrite(buffer, 1, 512, point);
            fclose(point);
        }
        else if (files >= 0) // if it is part of a previous picture, add to it
        {
            FILE *point = fopen(name, "a");
            fwrite(buffer, 1, 512, point);
            fclose(point);
        }
    }
    fclose(card);
}