Search code examples
ccs50recover

cs50 recover, "recovered images do not match"


My source code successfully compiles and produced in a total of 50 pictures.
However, none of the recovered images do match the original image.
All of the jpegs look like these below.
As you can see, they seem to have weird edges overlapping.
Some of them look okay, but still fail to match the original picture.

enter image description here enter image description here

If you can give any insight on how to debug, please let me know.

Here is my code

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

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./recover image\n");
        return 1;
    }

    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
    {
        printf("Could not open %s.\n", argv[1]);
        return 1;
    }

    typedef uint8_t BYTE;
    BYTE buffer[512];
    char *filename[8];
    int jpeg_counter = 0;
    bool foundStartOfJPEG = false;
    FILE *img;

    // read memory card until the end of file
    while(fread(buffer, sizeof(BYTE) * 512, 1, file) == 1)
    {
        // if buffer has a signature of JPEG file,
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && ((buffer[3]) & 0xf0) == 0xe0)
        {
            if (foundStartOfJPEG == true)
            {
                fclose(img);
                jpeg_counter += 1;
            }

            foundStartOfJPEG = true;
            // create a file with index
            sprintf(*filename, "%03i.jpg", jpeg_counter);
            // open that file to write into it
            img = fopen(*filename, "w");
            // write the block of memory (buffer), to that file
            fwrite(buffer, sizeof(buffer), 1, img);
        }
        else if (foundStartOfJPEG == true)
        {
            fwrite(buffer, sizeof(buffer), 1, img);
        }
    }

    fclose(file);
    return 0;
}

Solution

  • I tried out your code and it works when you change filename from a pointer to an array (i.e. char *filename to char filename).