1

Everything else works in my code, no memory leaks, all other images are loaded properly, except the first one. I've gone through debug50 to try and see the problem, but I can't seem to find one since there appears to be bytes being saved to the first image from the buffer. Anything I'm missing? (sorry about my long comments :P)


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

const int BLOCK_SIZE = 512;

int main(int argc, char *argv[])
{
    // Check if one command line argument is given
    if (argc != 2)
    {
        printf("Usage: ./recover IMAGE\n");
        return 1;
    }

    // Open file and check that it exists
    FILE *raw_file = fopen(argv[1], "r");
    if (raw_file == NULL)
    {
        printf("File cannot be opened\n");
        return 1;
    }

    char * name = malloc(8); //save names of files in, saves 8 bytes bc 3 numbers, .jpg, and the /0
    int number = 0; //for naming the files numbers
    sprintf(name, "%03d.jpg", number); //save number.jpg to name (%03d makes the number have 3 decimal places)
    FILE * output = fopen(name, "w"); //make the file called (whatever's saved in name) for writing in
    unsigned char buffer[BLOCK_SIZE]; //initialize the buffer to read blocks into

    // while fread successfully reads 512 bytes into buffer
    while (fread(buffer, 1, BLOCK_SIZE, raw_file) == BLOCK_SIZE)
    {
        // Check if the buffer contains the start of an image and make a new one if it does
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && buffer[3] >= 0xe0 && buffer[3] <= 0xef)
        {
            if (number != 0)
            {
                fclose(output);
                sprintf(name, "%03d.jpg", number);
                output = fopen(name, "w");
            }
            number++;
        }

        fwrite(&buffer, BLOCK_SIZE, 1, output);

    }

    //close any open files
    fclose(output);
    fclose(raw_file);
    //free malloc memory
    free(name);
}

My second image looks like this (001.jpg):

001

My last image looks like this (049.jpg):

049

1 Answer 1

3

Simple logic error. Look at the following:

    {
        if (number != 0)
        {
            fclose(output);
            sprintf(name, "%03d.jpg", number);
            output = fopen(name, "w");
        }                 // MOVE THIS CURLY BRACE - cliffb
        number++;
    }

this is the code that opens the output file. It correctly won't attempt to close the prior file for the first output file because it doesn't exist. The problem is that it also doesn't allow a new file to be opened when number = 0.

Simple fix. Move the inner curly brace up two lines, between the fclose and sprintf lines.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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