My code below compiles and generates 50 images, but all appear blurry or are a coloured mess.
I've tried debugging but without success. I must be missing a logical step. May anyone advise?
#include <stdlib.h>
// Initialize variables.
char fileName[8];
int numberOfJpegsFound = 0;
FILE *img = NULL;
int main(int argc, char *argv[])
{
// Validate command line argument.
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
// Open the memory card - exit program if error
FILE *file = fopen(argv[1], "r");
if (file == NULL)
{
printf("Failed to read image.\n");
return 1;
}
// Initialize buffer for storage.
unsigned char buffer[512];
// Read 512 bytes until memory card finishes.
while (fread(buffer, 512, 1, file) > 0)
{
// Assess if first 512 bytes is a JPEG header
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// If first JPEG is found, write the first file
if (img == NULL)
{
sprintf(fileName, "%03i.jpg", numberOfJpegsFound);
img = fopen(fileName, "w");
fwrite(buffer, 512, 1, img);
}
// Close current image, increment counter, and write an additional new file
else
{
fclose(img);
numberOfJpegsFound++;
sprintf(fileName, "%03i.jpg", numberOfJpegsFound);
img = fopen(fileName, "w");
fwrite(buffer, 512, 1, img);
}
}
// Continue writing to current JPEG file.
else if (img != NULL)
{
img = fopen(fileName, "a");
fwrite(buffer, 512, 1, img);
}
}
return 0;
}