My code compiles and runs without any errors. Images are generated, but the images are incomplete, here's an example of 000.jpg: https://i.sstatic.net/gCTju.png. I can't really find what's wrong in my code, any help is appreciated!
#include <string.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage: recover <raw_file>\n");
return 1;
}
// open input file
FILE *inptr = fopen(argv[1], "r");
if (inptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", argv[1]);
return 2;
}
int jpegsFound = 0;
unsigned char buffer[512];
FILE *img;
while (fread(&buffer, 1, 512, inptr) == 512)
{
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// Block consists header of a new jpeg file
if (jpegsFound > 0)
{
// Already found image, should close now
fclose(img);
}
jpegsFound++;
// Now handle the new file
char filename[8]; // 000.jpg\0
sprintf(filename, "%03i.jpg", jpegsFound - 1); // Start from 000.jpg
img = fopen(filename, "w");
if (img == NULL)
{
fclose(img);
fprintf(stderr, "Could not create %s.\n", filename);
return 3;
}
fwrite(&buffer, sizeof(buffer), 1, img);
}
if (jpegsFound > 0)
{
// A continued data of the last image
fwrite(&buffer, sizeof(buffer), 1, img);
}
// Clears the buffer
memset(&buffer, 0, 512);
}
fclose(inptr);
fclose(img);
return 0;
}