Help needed with recover part of pset4. Please find my code below. It compiles but produces a seg fault. Any comments are welcome. Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char *argv[])
{
//check for right number of command line arguments.
if (argc != 2)
{
printf("File name missing!\n");
EXIT_FAILURE;
}
//open card file to read.
FILE *file = fopen (argv[1], "r");
//if card empty, flag error, exit program.
if (file == NULL)
{
printf("Could not open file %s\n", argv[1]);
EXIT_FAILURE;
}
//create empty file to store retrieved images.
FILE *retrieved = NULL;
//create buffer array and image filename array.
char filename[13];
unsigned char buffer[512];
//create counter for retrieved images.
int count_ret = 0;
//boolean value to indicate the end of an image.
bool end_of_image = false;
//start reading card.
while (fread(buffer, 512, 1, file) == 1)
{
//check if at start of new jpeg.
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & (0xf0 == 0xe0)))
{
//At this point, we do not know if this jpeg is the first, nor can we assume so.
//To make sure, we check if the bool is true, pointing to the end of a JPEG.
//We subsequently switching it to 0 and start writing in our retrieved images file.
if (end_of_image == true)
{
fclose(retrieved);
}
else
{
//closed file means end of image is reached.
end_of_image = true;
}
sprintf(filename, "%03i.jpg", count_ret);
retrieved = fopen(filename, "w");
count_ret ++;
}
if(end_of_image == true)
{
fwrite(&buffer, 512, 1, retrieved);
}
}
fclose(file);
fclose(retrieved);
return 0;
}