#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
//Creates a new variable BYTE that stores a BYTE of data
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
    //Incorrect Number of CLA
    if (argc != 2){
        printf("Improper Usage\n");
        return 1;
    }
    //Incorrect Files Inputted
    if (argv[1] == NULL){
        printf("Usage: ./recover IMAGE\n");
    }
    //initializing the buffer
    BYTE buffer[512];
    //Open the Memory Card and Initialize the file pointer pointing towards it ----- fread
    FILE *f = fopen(argv[1], "r");
    //variable for filename
    int count = 0;
    //create a new block of memory to store the filename
    char *filename = malloc(8);
    //Set the name of the string to later name the file
    sprintf(filename, "%03i.jpg", count);
    //creating a new file with the name set
    FILE *new_file = fopen(filename, "w");
    if (new_file == NULL) {
        fprintf(stderr, "Failed to open file: %s\n", filename);
        free(filename);
        fclose(f);
        return 1;
    }
    //while loop that runs till the end of the file
    while (fread(buffer, 1, 512, f) == 512){
        //Look for the beginning of a JPEG file ( 0xff, 0xd8, 0xff, 0xe0) ----- &0xf0
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0){
            if (count == 0){
                //writing the block of 512 bytes to the new file
                fwrite(buffer, 1, 512, new_file);
                //increase the count according to the number of file
                count++;
            } else {
                fclose(new_file);
                sprintf(filename, "%03i.jpg", count);
                count++;
                new_file = fopen(filename, "w");
                fwrite(buffer, 1, 512, new_file);
            }
        }else{
            //writing the data contiguosly stored in the memory card
            fwrite(buffer, 1, 512, new_file);
        }
    }
    //free
    fclose(f);
    fclose(new_file);
    free(filename);
}
Since the problem is arising with the first jpeg 000.jpg, I'm guessing it has got something to do with the if (count == 0) part. But can seem to figure it out. I have tried to initialize new_file outside the while loop and opening it in the if cond. but it not working.
Please tell me what could be the problem.
 
    