Search code examples
ccs50data-recovery

PSET4 RECOVERY does not recover images correctly


I have started working on PSET 4 RECOVERY. My program compiles successfully, it goes through the first 3 tests no problem, but for the love of me I cannot seem to find the problem. It just does not correctly restore the photos, I have tried changing ptr to char and vice versa to no avail.

Here is the code:

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

typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
    //check for number of arguments
    if (argc != 2)
    {
        printf("Usage: ./recover filename\n");
        return 1;
    }
    //initialize files
    char *input_name = argv[1];
    FILE *input = fopen(input_name, "r");
    if (input == NULL)
    {
        //check if file is openable
        printf("File %s could not be opened!", input_name);
        return 1;
    }
    //initialize files and pointers
    BYTE file[512];
    int counter = 0;
    FILE *img = NULL;
    char img_name[8];
    //loop as long as files returns bytes
    while(fread(&file, 512, 1, input) == 1)
    {
        //check if file is jpeg
        if (file[0] == 0xff && file[1] == 0xd8 && file[2] == 0xff && (file[3] & 0xf0) == 0xe0)
        {
            //if a previous file is open, close it
            if (counter != 0)
            fclose(img);
        }
        //initialize new file
        sprintf(img_name, "%03i.jpg", counter);
        img = fopen(img_name, "w");
        counter++;
        //if jpeg is found, write
        if (counter != 0)
        {
            fwrite(&file, 512, 1, img);
        }
    }
        fclose(input);
        fclose(img);
        return 0;

Any help is appreciated


Solution

  • So you have this check in place to see if you found the start of a new image. And if you find a new image, you want to open it. But look at where that branch ends. You check whether it's the start of a new image, then you check if an image needs to be closed. And then you end both branches. You unconditionally open a new image every time your loop runs. The whole, and only error here, is the location of a curly brace.

    //check if file is jpeg
    if (file[0] == 0xff && file[1] == 0xd8 && file[2] == 0xff && (file[3] & 0xf0) == 0xe0)
    {
        //if a previous file is open, close it
        if (counter != 0)
        fclose(img);
    } // <- !! what !!
    //initialize new file
    sprintf(img_name, "%03i.jpg", counter);
    img = fopen(img_name, "w");
    counter++;
    //if jpeg is found, write