So, I've been struggling with this bug for a couple days now and can't seem to figure out how to fix it. I've also noticed that the final image file is WAY larger than any of the other jpg's my program spits out, so my reasoning is that the program doesn't know when to stop writing to the image file and close it, as it never encounters another JFIF header. I experimented with a couple of functions that try to identify "zeroed" blocks of memory, so that they don't end up on the final image, but even then, 049.jpg still comes out with around 3.2 megabytes of size, while the other files measure around 30~50 kb.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int size(FILE *file);
int check_zero(BYTE buffer[512]);
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
FILE *file = fopen(argv[1], "r");
if (file == NULL)
{
return 1;
}
BYTE buffer[512];
double file_size = size(file);
int jpeg_count = 0;
FILE *image;
for (int i = 0; i < file_size; i++)
{
fread(buffer, 1, 512, file);
if ((buffer[0] == 0xff) && (buffer[1] == 0xd8) && (buffer[2] == 0xff) && ((buffer[3] & 0xf0) == 0xe0))
{
char name[7];
if (jpeg_count == 0)
{
sprintf(name, "%03i.jpg", jpeg_count);
image = fopen(name, "w");
fwrite(buffer, 1, 512, image);
}
else
{
fclose(image);
sprintf(name, "%03i.jpg", jpeg_count);
image = fopen(name, "w");
fwrite(buffer, 1, 512, image);
}
jpeg_count++;
}
else if (jpeg_count > 0)
{
if (check_zero(buffer) == 1)
{
if (image != NULL)
{
fclose(image);
}
}
else
{
fwrite(buffer, 1, 512, image);
}
}
}
}
int size(FILE *file)
{
BYTE buffer[512];
int file_size = 0;
do
{
file_size++;
}
while(fread(buffer, 1, 512, file) == 512);
rewind(file);
return file_size;
}
int check_zero(BYTE buffer[512]) // Checks if memory block is zeroed
{
for (int i = 0; i < 512; i++)
{
if (buffer[i] == 00000000)
{
}
else
{
return 0;
}
}
return 1;
}