The code compiles fine but when running ./recover i keep getting a seg fault. i tried valgrind but still can't seem to get what the problem is exactly.

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

#define BLOCKSIZE 512

typedef uint8_t BYTE;

int main(int argc, char *argv[])
    if (argc != 2)
        printf("Usage: ./recover image");
        return 1;
    char *infile = argv[1];
    FILE *inptr = fopen(infile, "r");
    if (infile == NULL)
        return 2;
    BYTE buffer[512];
    int jpegcount = 0;
    char filename[8];
    FILE *outptr = NULL;
        size_t bytesr = fread(buffer, sizeof(BYTE), BLOCKSIZE, inptr);
        if (bytesr == 0 && feof(inptr))
        bool jpegheader = (
            buffer[0] == 0xff && 
            buffer[1] == 0xd8 && 
            buffer[2] == 0xff && 
            (buffer[3] & 0xf0) == 0xe0);
        if (jpegheader == true && outptr != NULL)
        if (jpegcount == true)
            sprintf(filename, "%03i.jpg", jpegcount);
            outptr = fopen(filename, "w");
        if (outptr != NULL)
            fwrite(buffer, sizeof(BYTE), bytesr, outptr);
    return 0;

Well couple of bugs I noted.

  • Why are you declaring a string pointer and use it as a pointer to a file simply you can use FILE *fp = fopen(// do something);

  • Why are declaring two file pointers, actually one file pointer is enough to open and close a file and read or write on files

  • You continuously need to read the block of 512 bytes of card.raw till it reaches the EOF (end of the file) and store it in a buffer to work with it

read fread() function documentation for a brief guide or simply

fread(where_to_store, size_of_each block, blocks_to_read, where_to_read);

If I helped you be sure to tick the answer to keep other smiling too 😃

You must log in to answer this question.

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