I read several questions related to the segmentation fault but still cannot figure out what exactly is wrong with my code. Basically, what happens is that the program recovers around 10 photos correctly and then it crashes at line 36 (just after the initialization of the counter) with a "No such file or directory" message at gdb. Although it recovers clearly these photos it doesn't pass the check50 (gets "killed by server"). Thank in advance for any input! :)
int main(int argc, char* argv[])
{
unsigned char buffer[512];
//open the file (card.raw)
FILE* file = fopen("card.raw", "r");
if (file == NULL)
{
printf("Could not open file.\n");
return 2;
}
//create and open output file where we're going to write
char filename[8];
FILE* outptr= NULL;
outptr=fopen(filename,"w");
int counter = 0;
while (!feof(file))
{
fread(&buffer,512,1,file);
//track for jpg signature
if(buffer[0]==0xff && buffer[1]==0xd8 && buffer[2]==0xff && (buffer[3]==0xe0 || buffer[3]==0xe1))
{
//close previous file if opened
if(outptr!=NULL)
{
fclose(outptr);
}
//open a new one to write to
sprintf(filename,"00%d.jpg", counter);
outptr=fopen(filename, "w");
fwrite(&buffer,512,1,outptr);
counter++;
}
//if no jpg signature is found yet,
else
{
fwrite(&buffer,512,1,outptr);
}
}
fclose(file);
// close outfile
fclose(outptr);
return 0;
}