0

I recently started with CS50 and I struggle a bit with pset4's recover. While the jpgs look correct to me, my code only recovers 49 jpgs total, not the 50 which are expected. Check50 fails on the first jpg as well. Any help?

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

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

    // Open file
    FILE *card = fopen(argv[1], "r");

    if (!card)
    {
        return 2;
    }

    typedef uint8_t BYTE;
    BYTE buffer[512]; int jpg_1 = 0; int counter = 0; FILE *new_img;
    while (fread(buffer, 1, 512, card) != EOF)
    {
        // Checking the header of the file
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            // If it's the 1st file
            if (!jpg_1)
            {
                jpg_1 = 1;
                char name[8];
                sprintf (name, "%03i.jpg", counter++);
                new_img = fopen(name, "w");
                fwrite(buffer, 1, 512, new_img);


            }
            else
            {
                // If it's the next file
                fclose(new_img);
                char name[8];
                sprintf (name, "%03i.jpg", counter++);
                new_img = fopen(name, "w");

                if (new_img == NULL)
                    return 3;

                // Write to the file
                fwrite(buffer, 1, 512, new_img);
            }
        }
        else
        {
            if (jpg_1 == 1)
            {
                // Continue to write in the same file
                fwrite(buffer, 1, 512, new_img);
            }
        }
    }

    // Close the file
    fclose(new_img);
    fclose(card);
}
0

The fread function per its specification returns a value denoting the total number of elements successfully read. Since you read 512 characters every iteration of the loop, it must quit when the function returns a value other than 512. Fix this line of code and your program should run fine: while (fread(buffer, 1, 512, card) != EOF)

2
  • Thank you at first, I've read these specifications but didn't manage to find absolute answer to what is really wrong. May I ask about why fread must quit when the function returns a value other than 512? It may return a value less than 512 but I think it should continue to read until End Of File is reached. What do you think? – Abdallah Elbradey Apr 1 '20 at 22:44
  • The problem tells you that the bits come in groups of 512, so this is a solution most people decide to use. You could definitely implement your own method, but it would be more difficult. You must check the buffer array for the end of file character. – TLH Apr 2 '20 at 9:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .