So my recover.c worked and recovered all 50 photos, all of them are viewable. The program also passed Valgrind test with no leak in memory. However, it didn't pass check50 test. The results are:
:) recover.c exists
:) recover.c compiles
:) recovers 000.jpg correctly
:( recovers middle files correctly
:( recovers last file correctly
\ expected 015.jpg to exist
Actually, 015.jpg is right there and viewable. I was wondering if you could help. I am posting the code here (includes: stdio.h, stdlib.h). Thank you very much!
typedef uint8_t BYTE;
typedef int32_t LONG;
int main(void)
{
char* infile = "card.raw";
int count = 0; // record the number of photos recovered
// open input file for JPEG checking
FILE* inptr = fopen(infile, "r");
if (inptr == NULL)
{
printf("Could not open %s.\n", infile);
return 2;
}
char outfile[10]; // name of recovered JPEG photo
LONG read_tag;
FILE* outptr = NULL;
// read through input file
while(!feof(inptr))
{
fread(&read_tag, sizeof(LONG), 1, inptr);
if(read_tag == 0xe0ffd8ff) // check whether the first 4 bytes correspond to the signature of a JPEG file
{
fseek(inptr, -sizeof(read_tag), SEEK_CUR); //go back to the beginning of this 512B block for copying
if(outptr != NULL) // if the file of previously found JPEG file is still open, close it
fclose(outptr);
sprintf(outfile, "%03d.jpg", count); // create new JPEG file
count++; //found one JPEG
outptr = fopen(outfile, "a");
if (outptr == NULL)
{
fclose(inptr);
fprintf(stderr, "Could not create %s.\n", outfile);
return 3;
}
BYTE* buf; // copy the content to this JPEG file
for(int j = 0; j < 512; j++)
{
fread(&buf, sizeof(BYTE), 1, inptr);
fwrite(&buf, sizeof(BYTE), 1, outptr);
}
}
else if(count > 0) // if it is a 512B block after JPEG signature, copy the content to newly created file
{
fseek(inptr, -sizeof(read_tag), SEEK_CUR);
BYTE* buf;
for(int j = 0; j < 512; j++)
{
fread(&buf, sizeof(BYTE), 1, inptr);
fwrite(&buf, sizeof(BYTE), 1, outptr);
}
}
else // if this 512B block is before the first JPEG file, skip it and go to the next 512B block
{
fseek(inptr, sizeof(BYTE) * 508, SEEK_CUR);
}
}
fclose(outptr);
fclose(inptr);
}