I've been working on Recover a few days now and managed to actually create a program that retrieves the images. The only problem is that they are not retrieved correctly and don't match what they are actually supposed to be. After running debugger, it continues to land on the line "while (fread(buffer, sizeof(buffer), 1, inputfile) == 1)". I have changed that line so many times, but everytime I change it (along with other lines of code), but everytime I do, I get a segmentation fault. I have no idea what to do. Any help would be greatly appreciated!
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <stdint.h>
#define BLOCKSIZE 512
typedef uint8_t BYTE;
bool found_jpeg(BYTE buffer[])
{
return (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0);
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
FILE *inputfile = fopen(argv[1], "r");
if (inputfile == NULL)
{
printf("File not found\n");
return 1;
}
else
{
BYTE buffer[BLOCKSIZE];
FILE *outputfile = NULL;
char filename[8];
int counter = 0;
bool first_jpeg = false;
while (fread(buffer, sizeof(buffer), 1, inputfile) == 1)
{
if (found_jpeg(buffer) == true)
{
if (first_jpeg == false)
{
sprintf(filename, "%03i.jpg", counter);
outputfile = fopen(filename, "w");
if (outputfile == NULL)
{
return 1;
}
fwrite(buffer, sizeof(buffer), 1, outputfile);
counter++;
first_jpeg = true;
}
else if (first_jpeg == true)
{
fclose(outputfile);
sprintf(filename, "%03i.jpg", counter);
outputfile = fopen(filename, "w");
if (outputfile == NULL)
{
return 1;
}
fwrite(buffer, sizeof(buffer), 1, outputfile);
counter++;
}
}
if (first_jpeg == true)
{
fwrite(buffer, sizeof(buffer), 1, outputfile);
}
}
fclose(outputfile);
fclose(inputfile);
}
}