I have run my program and it works (at least looks like). My code recovered all the 000.jpg to 049.jpg. The 50 jpgs show in the "jpg folder, and I can see all the 50 faces of the teaching team.
However, the check code says the code recovers the 000.jpg correctly but fails to recover the middle and the last jpg.
I tried GDB, GDB shows the process exits normally. But if I set a breakpoint to main and run step by step, it seems to be trapped in the first loop.(I don't get why it can exits normally while trapped in a loop)
So I desperately don't have any other resort.
Here's my questions:
- I do not define how long is my BLOCK, how could the code know and read and write the 50 images?
2.How could the code successfully recovers the 000.jpg but fails at the middle and the last? (and yet the images all look fine, clear and viewable)
Thanks
Here's my code:
/**
* recover.c
*
* Computer Science 50
* Problem Set 4
*
* Recovers JPEGs from a forensic image.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
typedef struct
{
BYTE byte_1;
BYTE byte_2;
BYTE byte_3;
BYTE byte_4;
BYTE* body[];
} __attribute__((__packed__))
BLOCK;
int main(void)
{
// open the input file
FILE* file = fopen("card.raw", "r");
if (file == NULL)
{
printf("Could not open card.raw\n");
return 1;
}
BLOCK block;
do
{
fread(&block, sizeof(BLOCK), 1, file);
}
while (block.byte_1 != 0xff || block.byte_2 != 0xd8 || block.byte_3 != 0xff || (block.byte_4 < 0xe0 || block.byte_4 > 0xef));
//open new file
char* tittle = malloc(7 * sizeof(BYTE));
int photo_recovered = 0;
sprintf(tittle, "%03d.jpg", photo_recovered);
FILE* img = fopen(tittle, "w");
fwrite(&block, sizeof(BLOCK), 1, img);
while (fread(&block, sizeof(BLOCK), 1, file) == 1) //read a block and check the condition
{
//when the next ID is detected
if (block.byte_1 == 0xff && block.byte_2 == 0xd8 && block.byte_3 == 0xff && 0xe0 <= block.byte_4 && block.byte_4 <= 0xef)
{
fclose(img);
photo_recovered = photo_recovered + 1;
sprintf(tittle, "%03d.jpg", photo_recovered);
img = fopen(tittle, "w");
fwrite(&block, sizeof(BLOCK), 1, img);
}
//if no ID detected
else
{
fwrite(&block, sizeof(BLOCK), 1, img);
}
}
free(tittle);
fclose(file);
fclose(img);
return 0;
}