0

Recover perfectly recovers all 16 jpgs, but fails the last 3 checks in . https://sandbox.cs50.net/checks/d8b30ce483964703917dc0153b9d0d2e

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

typedef uint8_t BYTE;

int main(int argc, char* argv[])
{
    // open file
    FILE* input = fopen("card.raw", "r");

    // check for error while opening file
    if (input == NULL)
    {
        printf("Couldn't open file.");
        fclose(input);
        return 1;
    }

    BYTE buf[512];
    int file_counter = 0;
    FILE* jpg = NULL; 

    // read file until EOF  reached
    while (!feof(input))
    {
        fread(&buf, 512, 1, input);

        if (buf[0] == 0xff && buf[1] == 0xd8 && buf[2] == 0xff &&
            (buf[3] == 0xe0 || buf[3] == 0xe1))
        {
            char jpg_name[4];
            sprintf(jpg_name, "0%i.jpg", file_counter);
            jpg = fopen(jpg_name, "w+");
            file_counter++;
        }
        if (jpg != NULL)
        {
            fwrite(&buf, 512, 1, jpg);
        }
        else
        {
            continue;
        }    

    }

    fclose(jpg);
    fclose(input);
    return 0;
}

1 Answer 1

0
  1. if input is NULL you don't need to fclose it because it did not open at the first place.
  2. you are sort of misusing feof. see why?
  3. you are not naming the files correctly. see the specs for more info on what the names should be.
  4. you are trying store more characters into jpg_name that it is capable of storing.
  5. you are only closing the last JPG.
  6. you do not need the else block at the end of the while loop.
1

You must log in to answer this question.

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