I 'm getting a segmentation fault for my recover code. I know that it's wrong, and I think that this boils down to me not really understanding how to apply pointers/file functions. Maybe you could give me some pointers on what I don't seem to understand? I haven't put in any code for checking the argc input yet since I can't get this recover part down.
{
//makes sure that the file is not null
FILE *f = fopen("argv[1]", "r"); //opens a file
int *buffer = malloc(512);
if (buffer==NULL)
{
printf ("failed");
return 1;//failed
}
else
{
char check;
char filename[8];
char prevfile[8];
int i = 0;
sprintf(filename, "%03i.jpg", i); //file is named here
sprintf(prevfile, "%03i.jpg", i-1); //the file that will need to be closed
while ((check = fgetc(f)) != EOF)//while the EOF has not been reached
{
fread (buffer, 512, 512*50, f);//read file f into a buffer in 512 byte chunks
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) //if the header is present
{
if (i == 0)//if this is the first jpg, open 000.jpg and start writing into this file
{
FILE *img = fopen(filename, "w"); //the img, heretofore unnamed, is opened for writing
fwrite (buffer, 512, 1, img); //fwrite for the 000.jpg
}
else //else this is the nth jpg, close 0xx.jpg, open jpg, and start writing into a new file
{
FILE *img = fopen(filename, "w"); //open 0xx.jpg
fwrite (buffer, 512, 1, img);
}
i++;
}
else
{
//if file is already open
{
FILE *img = fopen(prevfile, "a");
fwrite (buffer, 512, 1, img);
}
}
}
}
free(buffer);
}