0

Although my code works fine, It is recovering all 16 images correctly. But when I try to check it with check50 command in command prompt, it prompts error saying that 015.jpg is not recovered properly. But in folder it is there, I just don't understand why its happening.

enter image description here

/**
 * recover.c
 *
 * Computer Science 50
 * Problem Set 4
 *
 * Recovers JPEGs from a forensic image.
 */
#include <stdio.h>
#include <stdint.h>
int main(void)
{   
    // open input file
    FILE* inptr = fopen("card.raw", "r");

    if (inptr == NULL)
    {
        printf("Could not open card.raw\n");
        return 1;
    }

    // counter
    int count = 0;

    /* a block of 512 bytes (Different datatypes have different size here we explicitly 
       need a datatype which stroes each element in a BYTE) */
    uint8_t block[512];

    // output file
    FILE* outptr = NULL; 

    do
    {
        fread(block, 512, 1, inptr);

        // are we at the start of a JPG ?
        if (block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] == 0xe0 || block[3] == 0xe1))
        {
            // if already exist, then close file
            if (outptr != NULL)
            {
                fclose(outptr);    
            }  

            // what file should we put data into
            char FILENAME[8];
            sprintf(FILENAME, "%03d.jpg", count);
            outptr = fopen(FILENAME, "w");
            count++;

            fwrite(block, sizeof(block), 1, outptr);
        }
        else if (count > 0)
        {
            // put jpg into outptr
            fwrite(block, sizeof(block), 1, outptr);
        }
    }while(!feof(inptr));

    // close infile
    fclose(inptr);

    // close outfile
    fclose(outptr);

    // that's all folks
    return 0;
}
1

The problem lies in the do/while structure. You are executing one too many freads and processing the result. Instead of do/while(eof), try changing to a structure of while(fread) {...}. I'll leave it to you how to fill in the details. Don't want to give away too much. ;-)

If this answers your question, please click on the check to accept. Let's keep up on forum housekeeping. ;-)

1
  • Thanks it's fixed, It was executing one extra time.
    – user8269
    Oct 20 '15 at 10:10

You must log in to answer this question.