While using debug50 to check my code, I realized that it would encounter segmentation fault when it reaches "fwrite(buffer, 512, 1, photo);" for the second time. There's no problem on the first time though. Below is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover image\n");
return 1;
}
// remember filename
char *recovername = argv[1];
// open location
FILE *recover = fopen(recovername, "r");
unsigned char buffer[512];
if (recover == NULL)
{
fprintf(stderr, "Could not open %s.\n", recovername);
return 2;
}
int a=0;
// find
while (fread(buffer, 512, 1, recover) == 1)
{
//read file by 512 bytes
FILE* photo = NULL;
//check if it's a jpeg
if(buffer[0]==0xff && buffer[1]==0xd8 && buffer[2]==0xff && (buffer[3] & 0xf0)==0xe0)
{
if(a>0)
{
fclose(photo);
}
a++;
char filename[8];
sprintf(filename, "%03i.jpg",a);
photo = fopen(filename, "a");
}
if(a>0)
{
fwrite(buffer, 512, 1, photo);
}
}
// close infile
fclose(recover);
fclose(filename);
// success
return 0;
}