I am at Pset4 recover pset. When I run my code, it produces only 2 corrupted images
here is my code :
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
// validate input number
if( argc != 2)
{
printf("Usage: ./recover filename. \n");
return 1;
}
// validte recovery storage file
FILE *input = fopen(argv[1], "r");
if( input == NULL)
{
printf("Coudn't open file.\n");
return 1;
}
// read from input file
// placeholder from each img block == 512 bytes
BYTE bytes[512];
//images counter for naming
int numOfImgs = 0;
// placeholder for image name "string"
char filename[8];
// placeholder for image data to bestored before exporting to external file
FILE *img;
// check if reach ennd of memory card
while( fread(bytes, sizeof(bytes), 1, input) > 0)
{
// read 1 block from card
fread(bytes, sizeof(bytes), 1, input);
// current block is a starting of valid jpeg image
if( bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff && (bytes[3] & 0xf0) == 0xe0)
{
// if JPEG found is the first one
if( numOfImgs == 0)
{
// create a sequenced name
sprintf(filename, "%03i.jpeg",numOfImgs);
// open JPEG file to write in
img = fopen(filename, "w");
// write date in JPEG file
fwrite(bytes, sizeof(bytes), 1, img);
// increase number of found images
numOfImgs++;
} else
{
// if fond image is not the first which means there an image is currently open
// close the current opened image
fclose(img);
// create a sequenced name
sprintf(filename, "%03i.jpeg",numOfImgs);
// open JPEG file to write in
img = fopen(filename, "w");
// write date in JPEG file
fwrite(bytes, sizeof(bytes), 1, img);
// increase number of found images
numOfImgs++;
}
} else {
// if current block is not a valid start for a JPEG
// check if there is an open JPEG to add current block to
if( numOfImgs >= 0)
{
// add current block to opened JPEG
fwrite(bytes, sizeof(bytes), 1, img);
}
}
}
fclose(input);
fclose(img);
return 0;
}