I recently started with CS50 and I struggle a bit with pset3's recover. While the jpgs look correct to me, my code only recovers 49 jpgs total, not the 50 which are expected. Check50 fails on the first jpg as well. Could you take a look at my code and push me in the right direction? I really have no clue what went wrong here.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
// Make type BYTE
typedef uint8_t BYTE;
//function to check if the first bytes are jpg header bytes
int isJpg(BYTE *buffer);
int main(int argc, char *argv[])
{
// test for correct amount of arguments
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover file. Please try again.");
return 1;
}
// save file for reading
FILE *inptr = fopen(argv[1], "r");
// if inptr points to NULL exit program
if (!inptr)
{
fclose(inptr);
fprintf(stderr, "File could not be opened.");
return 2;
}
//allocate memory for the buffer
BYTE *buffer = malloc(512);
// Set counter to name the jpgs correctly
int counter = 0;
// Searching for a jpg
int searching = 1;
//make a string for the filenames
char filename[8];
// declare global variable, so it can be used in the while loop
FILE *img = NULL;
// read and write as long as EOF is not reached
while (fread(buffer, 1, 512, inptr) == 512)
{
if(searching)
{
// check if the first 4 Bytes match the jpeg header
if (isJpg(buffer))
{
//use sprintf to correctly name the file
sprintf(filename, "%03i.jpg", counter);
//create the file
img = fopen(filename, "w");
fwrite(buffer, 1, 512, img);
searching = 0;
}
}
else
{
if(isJpg(buffer))
{
fclose(img);
//use sprintf to correctly name the file
sprintf(filename, "%03i.jpg", counter);
//create the file
img = fopen(filename, "w");
//up the counter
counter++;
fwrite(buffer, 1, 512, img);
}
else
{
fwrite(buffer, 1, 512, img);
}
}
}
fwrite(buffer, 1, 512, img);
fclose(img);
//free allocated memory
free(buffer);
}
int isJpg(BYTE *buffer)
{
if (buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff &&
(buffer[3] & 0xf0) == 0xe0)
return 1;
else
return 0;
}