I'll attach some context in a comment because of word limit!
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./recover FILE\n");
return 1;
}
// Open the memory card
FILE *card = fopen(argv[1], "r");
// Create a buffer for a block of data
uint8_t buffer[512];
int jpeg_count = 0;
FILE *jpeg_file = NULL;
// While there's still data left to read from the memory card
while (fread(buffer, 1, 512, card) == 512)
{
// To create JPEG from the data do this:
// Look for the start of a JPEG
for (int i = 0; i < 512; i++)
{
if (buffer[i] == 0xff && buffer[i + 1] == 0xd8 && buffer[i + 2] == 0xff && (buffer[i + 3] & 0xf0) == 0xe0)
{
// Open a new JPEG file
char jpeg_filename[100];
sprintf(jpeg_filename, "%03d.jpg", jpeg_count++);
jpeg_file = fopen(jpeg_filename, "w");
// Write bytes of data from that JPEG until a new JPEG is found (identified from the start of a JPEG)
do
{
fwrite(buffer, 1, 512, jpeg_file);
}
while (fread(buffer, 1, 512, card) == 512 && !(buffer[i] == 0xff && buffer[i + 1] == 0xd8 && buffer[i + 2] == 0xff && (buffer[i + 3] & 0xf0) == 0xe0));
// Above line of code checks again to ensure that we have data to read. Also checks that there is no JPEG signature so that it continues writing until true
fclose(jpeg_file);
}
}
}
// This line should close the final image (image 49) since there will not be another JPEG signature.
if (jpeg_count > 0)
{
fclose(jpeg_file);
}
fclose (card);
}