Have spend the last 5 hours trying to figure out what am i doing wrong with my code, I seem to fail to understand what the mistake is in my logic, I am getting just 2 images as 000.jpg and 001.jpg both are correct, check50 is passing the first three tests but failing the last 2 tests obviously since there are only 2 files created but can't seem to understand why...HELP PLZZZZ
/**
* recover.c
*
* Computer Science 50
* Problem Set 4
*
* Recovers JPEGs from a forensic image.
*/
#include<stdio.h>
#include<cs50.h>
#include<stdint.h>
typedef uint8_t ONEBYTE;
int main(void)
{
// opening card
FILE* infile = fopen("card.raw", "r");
if(infile == NULL)
{
printf("could not open card.\n");
return 1;
}
/*declaring an array of characters to store 512 characters/bytes since char* points to
1st byte of array and the next bytes would follow consecutively */
ONEBYTE buffer[512];
//to track number of jpeg
int counter = 0;
// a filename where the string would be stored as filename
char filename[7];
//int c;
while(!feof(infile))
{
//reading data from card pointed by pointer infile in chunks of 512 Bytes one at a time and storing to buffer
fread(&buffer, 512 , 1, infile);
if((buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && buffer[3] == 0xe0) || (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && buffer[3] == 0xe1))
{
sprintf(filename, "%03i.jpg", counter);
FILE* outfile = fopen(filename, "w");
if(outfile == NULL)
{
printf("could not create a jpeg file.\n");
return 2;
}
counter++;
// writing to outputfile
fwrite(&buffer, 512, 1, outfile);
int i= 0;
while(counter !=0 && i== 0)
{
//to start reading after the first header of jpeg is found
fread(&buffer, 512, 1, infile);
//if it's the end of file than closing the last opened file
if(feof(infile) == EOF )
{
fclose(outfile);
i = 1;
}
//if its the start of a new jpeg
else if((buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && buffer[3] == 0xe0) || (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && buffer[3] == 0xe1))
{
//closing the previous output file
fclose(outfile);
i = 1;
}
else
{
fwrite(&buffer, 512, 1, outfile);
}
}
}
}
fclose(infile);
return 0;
}