0

This is my code for recover. When I run the program, it gives me 25 successfully recovered photos. I don't know why it is only giving me half the required photos. I believe it might have something to do with the way I handle subsequent/back-to-back jpeg files.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

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


    FILE *file = fopen(argv[1], "r");

    if (file == NULL)
    {
        printf("There was an error opening your forensic file.\n");
        return 1;
    }

    unsigned char bytes[PIC_BYTES];
    int file_number = 0;
    bool opened = false;
    FILE *jpegfile = NULL;
    char jpegname[8];

    while(fread(bytes, 512, 1, file) == 1)
    {
        if (opened == false && bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff && (bytes[3] & 0xe0) == 0xe0)
        {
            opened = true;
            sprintf(jpegname, "%03i.jpg", file_number);
            jpegfile = fopen(jpegname, "a");
            fwrite(bytes, 512, 1, jpegfile);
            file_number++;
        }

        else if (opened == true && (bytes[0] != 0xff || bytes[1] != 0xd8 || bytes[2] != 0xff))
        {
            fwrite(bytes, 512, 1, jpegfile);
        }

        else if (opened == true && bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff && (bytes[3] & 0xe0) == 0xe0)
        {
            fclose(jpegfile);
            opened = false;
        }


    }

    fclose(file);

}
0

Yeah, it's what you do with back-to-back files. Think about what happens if you're reading+writing jpg #0, and you find the start-of-jpg sequence. opened will be true, so you'll go into the second else if block, close jpg #0, and set opened to false. But you're not doing anything with the start-of-jpg sequence you just read. Then you'll go back to reading the next 512 bytes, and wait until you get the start-of-jpg sequence for jpg #2, but you totally skipped jpg #1.

According to the problem description, "each photo is stored immediately after the previously taken photo." (fourth paragraph in the background section), so you need to have a way to close the current jpg, and immediately start writing the next one.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .