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;
}