0

When I run my code, the program opens 49 jpg files but with the wrong headers (they do not start with 0xff, 0xd8, 0xff). I've run my program using gdb and it looks like those first 5 bytes are read correctly into the buffer, but after calling foundJPEG = fopen(number, "a")they change to random values.

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

//Function prototypes
bool trackChange(int count);


int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        fprintf(stderr, "Usage: ./recover file\n");
        return 1;
    }
    char *raw_data = argv[1];

    FILE *raw_file = fopen(raw_data, "r");
    if(raw_file == NULL)
    {
        fprintf(stderr, "Could not open file %s.\n", raw_data);
        return 2;
    }
    //Alocate buffer for one 512 byte block
    unsigned char buffer[512];
    //Keeps track of number of JPEG's that have been found
    int track = 0;

    FILE *foundJPEG = NULL;

    while(fread(buffer, 512, 1, raw_file) == 1)
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xe0) == 0xe0)
        {
            if(trackChange(track))
            {
                fclose(foundJPEG);
                sprintf(number, "%03d.jpg", track);
                char number[8];
                foundJPEG = fopen(number, "a");
                fwrite(&buffer, 512, 1, foundJPEG);
                track++;
            }
            else
            {
                char number[8];
                sprintf(number, "%03d.jpg", track);
                foundJPEG = fopen(number, "a");
                fwrite(&buffer, 512, 1, foundJPEG);
                track++;
            }
        }
        else
        {
            if(trackChange(track))
            {
                fwrite(&buffer, 512, 1, foundJPEG);
            }
        }   
    }

    fclose(foundJPEG);

    return 0;
}


bool trackChange(int count)
{
    if(count == 0)
    {
        return false;
    }
    else
    {
        return true;
    }
}

Any tips?

1 Answer 1

1

I ran the code above and, as written, it didn't compile because of the following:

        if(trackChange(track))
        {
            fclose(foundJPEG);
            sprintf(number, "%03d.jpg", track);
            char number[8];

The problem was that number was declared after it was used. By reversing the last two lines, it compiled successfully.

Once compiled, it worked fine for me. Is it possible that you are editing one version of the file and compiling and running another version in a different directory?

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 .