0

I wrote the below code and it recovers 51 images: 000.jpg to 050.jpg. All images except 000.jpg seems to have been found correctly. I'm not sure why the code isn't working?

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

//Define new data type BYTE
typedef uint8_t BYTE;

BYTE block[512];

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./recover filename\n");
        return 1;
    }
    //initialise items
    int counterjpg = 0;
    FILE *img = NULL;
    char filename[8];

    //create buffer
    BYTE *buffer = malloc(512);

    //Open memory card
    FILE *memorycard = fopen(argv[1], "r");

    //Check if memory card does not open
    if (memorycard == NULL)
    {
        printf("Error: cannot open file\n");
        return 1;
    }

    //Repeat until end of card
    while (!feof(memorycard))
    {

        //Read 512 bytes into buffer
        fread(buffer, 512, 1, memorycard);

        //If start of new jpeg
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            //If first jpeg
            if (counterjpg == 0)
            {
                sprintf(filename, "%03i.jpg", counterjpg);
                img = fopen(filename, "w");
                fwrite(buffer, 512, 1, img);
                counterjpg++;
            }

            //Else
            else
                //close current file
                fclose(img);

                //open new file
                sprintf(filename, "%03i.jpg", counterjpg);
                img = fopen(filename,"w");
                fwrite(buffer, 512, 1, img);
                counterjpg++;
        }
        //Else
        else
        {
            //If already found JPEG
            if (img != NULL)
            {
                //Keep writing to it
                fwrite(buffer, 512, 1, img);
            }
        }
    }
    free(buffer);
    fclose(memorycard);
    fclose(img);
    return 0;

}

2 Answers 2

0

You have 51 images can it be because 050.jpg is supposed to be 049.jpg and your 001.jpg is supposed to be your 000.jpg, check you initialization of your jpg counter

1
  • Thank you - I did think that. I think it is not showing in this code but I did initialise the counter: int counterjpg = 0; FILE *img = NULL; char filename[8]; So I'm not sure why it seems to count incorrectly?/ It looks like the first file is corrupted but subsequent ones work
    – Giulia
    Commented May 24, 2020 at 14:06
0

Worked it out - curly brackets around else statement were missing

You must log in to answer this question.

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