I have just spend hours trying to figure out why my program is giving out only 8 images (correct) instead of 15.Checked on the forums there were similar problems and the solution that I understood was that due to two consecutive freads one block is been skipped but can someone help me understand how the block is skipped in my code? The idea of my code is that freads a block if its end of file it breaks but if not it checks for the header if header is there opens a new file and writes the header to that file, then reads next block and keep on writing and reading blocks until next header comes
/**
* recover.c * * Computer Science 50 * Problem Set 4 * * Recovers JPEGs from a forensic image. */
include
include
include
int main(int argc, char* argv[]) { // open card file FILE* inptr = fopen("card.raw", "r");
// check for errors
if (inptr == NULL)
{
printf ("could not open card. \n");
return 1;
}
// declaring a block of 8 bits of Type BYTE and having 512 blocks
typedef uint8_t BYTE;
BYTE block[512];
FILE* picture ;
int counter = 0;
while (true)
{
fread(&block, 512, 1, inptr);
// checking for if end of data on card has reached.
if(feof(inptr))
{
break;
}
// checking for headers of JPEGs
if (block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] == 0xe0 || block[3] == 0xe1))
{
char name[9];
sprintf(name, "%03i.jpg", counter);
picture = fopen(name, "w");
fwrite(&block , 512, 1, picture);
// going on to next block
fread(&block, 512, 1, inptr);
//loop for keep on reading blocks by blocks after the header
while (!(block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] == 0xe0 || block[3] == 0xe1)))
{
fwrite(&block, 512, 1, picture);
fread(&block, 512, 1, inptr);
}
counter++;
}
}
fclose(picture);
}