So I am doing the CS50 practice problem of week 4. It’s about recovering a JPEG file that has been deleted so you enter the file check for 4 headers (first 3 the same and the 4th can vary but they gave you a solution) but the program is giving me a segmentation fault and I spend so much time debugging but still can’t figure it out. I’m new and any help is appreciated
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
//check for 2 command-line arguments
if (argc != 2)
{
printf("Input one command-line argumentn");
return 1;
}
FILE *f = fopen(argv[1], "r");
//the first 4 bytes which are the headers
BYTE b[4];
int filecounter = 0;
//a line from CHATGPT on how to check that I'm still not at the end of the file
while (fread(&b, sizeof(b), sizeof(b), f) == sizeof(b))
{
if (b[0] == 0xff && b[1] == 0xd8 && b[2] == 0xff && (b[3] & 0xf0) == 0xe0)
{
filecounter++;
char filename[10];
sprintf(filename, "%03i.jpg", filecounter);
FILE *img = fopen(filename, "w");
BYTE BLOCK[512];
//Same checking for end of File
if (fread(&BLOCK, sizeof(BLOCK), sizeof(BLOCK), f) != sizeof(BLOCK))
{
fclose(img);
fclose(f);
return 1;
}
fwrite(&BLOCK, 512, 512, img);
fclose(img);
}
}
fclose(f);
return 0;
}
I tried debugging on multiple lines of code but ended up having to remove most of the program for it to stop giving segmentation fault so I couldn’t really check where the error is.
greec_d is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.