Initially, I thought my code was only recovering 2 images from the card.raw file but after looking at the code with debug - I think it is recovering the 50 files but it overwrites 001.jpeg many times. When looking at program in debug, it seems like when a jpeg is found it steps into the if statement to create a file, creates the first file (000.jpeg) and increments file_number
, then finds the next file and writes it (001.jpeg) but every time it runs the sprintf
function to create the file name, it resets file_number
to 0. My question is why? I suspect it has something to do with the scope of the variable...?
// define a buffer array
unsigned char buffer[512];
// filename incrementing variable
int file_number = 0;
// create an array for filenames
char file_name[8];
while(fread(buffer, sizeof(buffer), 1, inptr) == 1)
{
// check buffer to see if it is a start of a jpeg
if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// close the file if it isn't the first jpeg
if(file_number > 0)
{
fclose(jpeg_file);
}
// create a name for the new file with format xxx.jpeg
sprintf(file_name, "%03i.jpeg", file_number);
// open a new file for writing jpegs
jpeg_file = fopen(file_name, "w");
if (jpeg_file == NULL)
{
fprintf(stderr, "Could not open %s.\n", file_name);
return 2;
}
// write the buffer into the file
fwrite(buffer, sizeof(buffer), 1, jpeg_file);
// increment the file counter
file_number++;
}
// write the buffer into the file if a jpeg have already been found
else if(file_number > 0)
{
// write the buffer into the file
fwrite(buffer, sizeof(buffer), 1, jpeg_file);
}
}