I'm having an issue with my code, and I was hoping you could help! I keep getting a segmentation fault error, and I'm not sure why. I've ran valgrind and according to its findings, the issue seems to be with my fwrite() function but I can't figure it out. Any help would be great, thanks!
#include <stdio.h>
#include <stdlib.h>
#define SIZE 512
int main(int argc, char *argv[])
{
//if there is not exactly 1 cl argument, it won't work
if(argc != 2)
{
printf("UNABLE TO COMPLY. FILENAME REQUIRED AT START\n");
return 1;
}
//START OF PROGRAM WITH VALID USER INPUT
if(argc == 2)
{
//open input file
char* input = argv[1];
FILE* card = fopen(input, "r");
//check if input is null
if(card == NULL)
{
printf("NO\n");
return 2;
}
//necessary components
unsigned char check[SIZE];q
int fileno = 0;
char filename[9];
FILE* img = NULL;
//read the check array 512 bytes at a time
while(!feof(card) && fread(check, SIZE, 1, card) == 1)
{
if(check[0] == 0xff && check[1] == 0xd8 && check[2] == 0xff && ((check[3] & 0xf0) == 0xe0) && fileno == 0)
{
sprintf(filename, "%03i.jpeg", fileno);
img = fopen(filename, "w");
fwrite(check, 1, SIZE, img);
fileno++;
}
else if(check[0] == 0xff && check[1] == 0xd8 && check[2] == 0xff && ((check[3] & 0xf0) == 0xe0) && fileno !=0)
{
fclose(img);
sprintf(filename, "%03i.jpeg", fileno);
img = fopen(filename, "w");
fwrite(check, 1, SIZE, img);
fileno++;
}
else
{
fwrite(check, 1, SIZE, img);
}
}
fclose(card);
fclose(img);
return 0;
}
}