guys I want to ask why am I constantly getting segfault with second fread inside of a while loop after checking jpeg header. first fread works perfectly going through first several 512bytes of card.raw. However entering in to while loop after header check, it crashes all the time whatever I try. First I tried malloc for image buffer and freed it before trying second fread which failed. Second, I tried appending output file using else if statements with only one fread function at the top which crashed also. Otherwise I tried several different methods whole weekend which I remember vaguely. Please help me to figure out any problem with my code. Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
FILE *inptr = fopen(argv[optind], "rb");
if (inptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", argv[optind]);
return 1;
}
char fc[3];
while (1)
{
uint8_t image[512];
fread(image, 1, 512, inptr);
int filecounter = 0;
if (image[0] == 0xff && image[1] == 0xd8 && image[2] == 0xff &&
image[3] >= 0xe0 && image[3] <= 0xef)
{
sprintf(fc, "%03i.jpg", filecounter);
char *outfile = fc;
FILE *outptr = fopen(outfile, "wb");
if (outptr == NULL)
{
fclose(outptr);
fprintf(stderr, "Could not create %s.\n", outfile);
return 1;
}
filecounter++;
int w = 0;
while (w == 0)
{
fwrite(image, 1, 512, outptr);
fread(image, 1, 512, inptr);
for(int i = 0; i < 511; i++)
{
if(image[i] == 0xff && image[i + 1] == 0xd9)
{
w = 1;
fwrite(image, 1, 512, outptr);
fclose(outptr);
break;
}
}
}
}
if(feof(inptr))
{
fclose(inptr);
return 0;
}
}
}