I have look at my code for a while now and for the life of me cannot find the bug.

When run, I am able to recover JPG's however only the upper left most portion reveals the picture, with the rest being gray space. To me this indicates a bug in the while loop that goes through the file 512 bytes at a time, but I am unable to find the issue.

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

int main(int argc, char *argv[])
    // Ensure proper usage
    if (argc != 2)
        fprintf(stderr, "Usage: One argument accepted.\n");
        return 1;

    // Open input file, checks if opened properly
    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
        fprintf(stderr, "Error: Could not open %s.\n", argv[1]);
        return 2;

    // Initialize buffer to 512 bytes
    uint8_t *buffer = malloc(sizeof(uint8_t)*512);

    // Initialize JPG counter
    int counter = 0;
    char filename[8];

    // Initiliaze JPG file ptr. Also used to track if previously opened
    FILE *img = NULL;

    /* Iterate through the raw file, looking for jpegs.
    Continues until chunk of 512 not read, indicating EOF
    while (fread(buffer, 512, 1, file))
        // If start of new JPG
        if( buffer[0] == 0xff &&
            buffer[1] == 0xd8 &&
            buffer[2] == 0xff &&
            (buffer[3] & 0xf0) == 0xe0)
            // Close previous image, if JPG already found
            if (img != NULL)

            // Initialize and attribute filename for jpg
            sprintf(filename, "%03i.jpg", counter);

            // Assign address to img pointer
            img = fopen(filename, "w");

            // Write the buffer into img file
            fwrite(buffer, 512, 1, img);

            // Increment counter

        // if JPG already found
        if (img != NULL)
            // Continue writing buffer into img
            fwrite(buffer, 512, 1, img);
    // No longer need memory allocated for buffer.
    return 0;

Any help would be greatly appreciated!

1 Answer 1


You write first sector twice for each file. Remove first fwrite(buffer, 512, 1, img);

And I'd put another if (img != NULL) in front of the second fclose(img); in case the dump contains no JPEG file at all.

You must log in to answer this question.

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