'Im having Problem With my code in C Error: sementaion Fault

When I run my code I gives me an error. Segmentation fault (core dumped)

here is my Code

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

typedef uint8_t BYTE;

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

    if(argc != 2) {

        printf("Usage: ./recover IMAGE");
        return 1;
    }

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

    if(file == NULL) {
        printf("chould not open file");
        return 2;


    }

    unsigned char buffer[512];

    int count = 0;

    FILE *output = NULL;

    char *filename = malloc(8 * sizeof(char));

    while (fread(buffer, 1, sizeof(char), file)) {

    if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) {

            sprintf(filename, "%03i.jpg", count);

             output = fopen(filename, "w");

             count++;
    }
    if(output == NULL) {
        fwrite(buffer, sizeof(char), 512, output);
    }

    }

    free(filename);
    fclose(output);
    fclose(file);

}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source