0

I have done my pset4 recover program, it seems to work, recovers 16 pictures and 15 of them are all right, but the first one is incorrect, and it says "Error interpreting JPEG image file (Invalid JPEG file structure: SOS before SOF)". I've been trying everything, searching on the internet, but I can't figure it out. My code:

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

int main(void)
{
// opens card
FILE* card = fopen("card.raw", "r");

if (card == NULL)
{
    printf("Could not open 'card'.\n");
    return 1;
}

// creates buffer
typedef uint8_t BYTE;
BYTE buffer[512]; 
int n = 0; // sets counter to zero

// creates file names
char image[8];
sprintf(image, "%03i.jpg", n);
FILE* jpeg = fopen(image, "w");

while (fread(&buffer, sizeof(buffer), 1, card) == 1)
{
    // if finds jpeg starting code
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
    {    
        // if file is already opened
        if ( n != 0)
        {
            fclose(jpeg);
        }
            // opens a new jpeg file
            sprintf(image, "%03i.jpg", n);
            FILE* jpeg = fopen(image, "w");

            // writes new jpeg
            n = n + 1;
            fwrite(&buffer, 512, 1, jpeg);
    }
    else if (n > 0)
    {
        fwrite(&buffer, 512, 1, jpeg);
    }

}
fclose(jpeg);
fclose(card);
return 0;
}
1

The problem is that you have created two file pointers called jpeg, FILE* jpeg = ... Since one is inside of a set of curly braces and the other is outside, both are allowed to be created. Initially, both are pointing at the same file and that is causing problems.

You need to remove the FILE* from the second statement to correct the problem. Also, you would do better to change the following:

sprintf(image, "%03i.jpg", n);
FILE* jpeg = fopen(image, "w");

That code is redundant and could present problems. It's better to set the pointer to NULL here to avoid introducing problems. Instead, replace them with:

FILE* jpeg = NULL;

That would get you going.

If this answers your question, please click the check mark and 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 .