I am working on PSET4 Recover from the CS50 course, but I can't seem to get it to work. I keep getting segmentation fault (core dumped). I've tried changing my code many times, but keep the segmentation fault. Can you spot where I go wrong? Thanks!
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <cs50.h>
typedef uint8_t BYTE;
const int FAT_SIZE = 512;
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./recover image");
return 1;
}
FILE *card = fopen(argv[1], "r");
if (card == NULL)
{
printf("Could not open file.\n");
return 1;
}
int n = 0;
string filename = "XXX.jpg";
BYTE temp[FAT_SIZE];
while (fread(temp, sizeof(BYTE), FAT_SIZE, card) == FAT_SIZE)
{
if(temp[0] == 0xff && temp[1] == 0xd8 && temp[2] == 0xff && (temp[3] & 0xf0) == 0xe0)
{
newfile:
sprintf(filename, "%03i.jpg", n);
FILE *output = fopen(filename, "w");
if (output == NULL)
{
fclose(card);
printf("Could not create new file.\n");
return 1;
}
fwrite(temp, sizeof(BYTE), FAT_SIZE, output);
while (fread(temp, sizeof(BYTE), FAT_SIZE, card) == FAT_SIZE)
{
if(temp[0] == 0xff && temp[1] == 0xd8 && temp[2] == 0xff && (temp[3] & 0xf0) == 0xe0)
{
fclose(output);
n++;
goto newfile;
}
fwrite(temp, sizeof(BYTE), FAT_SIZE, output);
}
fclose(output);
fclose(card);
return 0;
}
}
}