#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if(argc != 2)
{
fprintf(stderr, "Usage: ./recover <filename>\n");
return 1;
}
char *jpg = argv[1];
FILE *inptr = fopen(jpg, "r");
if (inptr == NULL)
{
fprintf(stderr, "Couldn't open the file\n");
return 2;
}
unsigned char buffer[512];
int jcount = 0;
char fname[7];
int stat = 0;
FILE *img;
while (fread(&buffer, 512, 1, inptr))
{
if (buffer[0] == 0x0ff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
if (stat == 1)
{
fclose(inptr);
sprintf(fname, "%03i.jpg", jcount);
img = fopen(fname, "a");
jcount++;
}
if(!stat)
{
sprintf(fname, "%03i.jpg", jcount);
img = fopen(fname, "w");
stat = 1;
jcount++;
}
fwrite(&buffer, 512, 1, img);
}
else
{
if (stat == 1)
{
fwrite(&buffer, 512, 1, img);
}
}
}
fclose(inptr);
fclose(img);
return 0;
}
Whats wrong with my code? Spent hours looking for a bug.