I am stuck in this problem, when I run it I keep getting a segmentation fault. I think that the bug in my code is in the while loop. In the walkthrough of the problem it was suggested to check if fread() returned a lower value than 512 to see wether we were or not at the end of the file. I tried to do so but I think the while may not be executed correctly. I would really appreciate it if someone could guide me on how to solve my bug, thank you in advance.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
//Open the file
FILE *f = fopen(argv[1], "r");
if (f == NULL)
{
printf("Error opening file");
return 2;
}
BYTE buffer[512];
char image[7];
int counter = 0;
FILE *pimage = NULL;
while (fread(&buffer, 1, 512, f) == 512)
{
fread(&buffer, 1, 512, f);
//Check if it is the start of a jpg file
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
//Check if it is the first jpg
if (counter == 0)
{
sprintf(image, "%03i.jpg", counter);
counter++;
pimage = fopen(image, "w");
fwrite(&buffer, 1, 512, pimage);
}
else
{
fclose(pimage);
sprintf(image, "%03i.jpg", counter);
counter++;
pimage = fopen(image, "w");
fwrite(&buffer, 1, 512, pimage);
}
}
else
{
fwrite(&buffer, 1, 512, pimage);
}
}
fclose(pimage);
}