Search code examples
ccs50recover

CS50 Pset4 Recover: recovers 049.jpg correctly, recovered image does not match


When try to submit, CS50 pset4 recover.c then got an error

:) recover.c exists. :) recover.c compiles. :) handles lack of forensic image :) recovers 000.jpg correctly :) recovers middle images correctly :( recovers 049.jpg correctly recovered image does not match

My code is

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define FAT 512

typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: name of forensic image from which to recover JPEGs");
        return 1;
    }
    FILE *file = fopen(argv[1], "r");
    if (!file)
    {
        fprintf(stderr, "Could not open %s.\n", argv[1]);
        fclose(file);
        return 2;
    }
    char *filename = malloc(50 * sizeof(int));

    BYTE buffer[FAT];
    if (!filename)
    {
        return 3;
    }
    FILE *curImg;
    int count = 0;
    while (!feof(file))
    {
        fread(buffer, sizeof(buffer), 1, file);
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if (count > 0)
                fclose(curImg);

            sprintf(filename, "%03i.jpg", count);
            curImg = fopen(filename, "w");
            if (curImg)
                fwrite(buffer, sizeof(buffer), 1, curImg);
            count++;
        }
        else
        {
            if (curImg)
                fwrite(buffer, sizeof(buffer), 1, curImg);
        }
    }
    free(filename);
    fclose(file);
    return 0;
}

I didn't understood, what's the problem. Anyone can help me?


Solution

  • It was happen for 'end of file indicator'. That means after writing file, something write in last file for a time. I just add a condition in

    if (curImg)
         fwrite(buffer, sizeof(buffer), 1, curImg);
    

    replace by

    if (curImg && !feof(file))
         fwrite(buffer, sizeof(buffer), 1, curImg);