why is this code giving me uncompleted photos?

Viewed 41

in this pset I should recover 50 every photo is 512 bytes, I should read the data from a file(argv[1]) then if I found a photo header I should write it to a file but it always gives me uncompleted photos any help would be appreciated

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


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

    FILE* out = NULL;
    int img_counter=  0;
    FILE* memorycard = fopen(argv[1], "r");
    if(memorycard == NULL)
    {
        printf("Could not open %s.", argv[1]);
        return 1;
    }
    BYTE img[512];
    char* filename = malloc(9 * sizeof(char));

    while (fread (img, 512, 1, memorycard) == 1)
    {
            if(img[0] == 0xFF && img[1] == 0xD8 && img[2] == 0xFF && (img[3] & 0xF0) == 0xE0)
            {
                sprintf(filename,"%03i.jpg",img_counter++);
                out = fopen(filename,"a");
                fwrite(img,512,1,out);
                fclose(out);
            }
    }
    fclose(memorycard);
    return 0;
    }
0 Answers
Related