recover.c CS50 blank images

25 Views Asked by At

I need help! I keep getting blank images when I run this code. I get all 50 images, so I know I screwed up with either fopen or fwrite, but I have spent hours with google bard and forums to no avail. I know its something stupid, so please be kind haha; my brain is much rn!

(ALSO, first stack overflow question, so apologies if I posted this incorrectly.)

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

int main(int argc, char *argv[])
{

    //checks input
    while (argc != 2)
    {
        printf("ERROR: Invalid command line argument, enter only 1 file.\n");
        return 1;
    }

    //opens memory card
    FILE *card = fopen(argv[1], "r");
    if (card == NULL)
    {
        printf("Error: opening file.\n");
        return 2;
    }

    //initializing loop variables
    uint8_t buffer[512];
    int counter = 0;
    FILE *recovered_jpeg;
    char filename[9];

    //reads memory card into buffer
    while (fread(buffer, 1, 512, card) == 512)
    {
        //check if file is a JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            //limits number of files
            if (counter > 999)
            {
                printf("Error: file overload.\n");
                return 3;
            }
            sprintf(filename, "%03d.jpeg", counter);
            counter++;

            //opens file for writing
            recovered_jpeg = fopen(filename, "w");
            if (recovered_jpeg == NULL)
            {
            printf("Error: opening file.\n");
            return 4;
            }

            //writes to new jpeg file
            fwrite(buffer, 512, 1, recovered_jpeg);
            fclose(recovered_jpeg);
        }
    }
    fclose(card);
    return 0;
}

I have reformatted and even copied different elements to no avail.

0

There are 0 best solutions below