0

I am working on pset4 recover in CS50 and I think I am almost done it. The files that it outputs though appear as a bunch of random symbols instead of a jpeg, I'm not sure why this is occurring but any help would be greatly appreciated.

I included my source code here:

if (argc != 2) 
{
    printf("Usage: ./recover image\n");
    return 1;
}

FILE *image = fopen(argv[1], "r");

if (image == NULL) 
{
    printf("Cannot obtain: %s", argv[1]);
    return 1;
}

FILE *imageNew = NULL;

typedef uint8_t BYTE;
active = false;
char filename[8];

BYTE buffer[512];

images = 0;


while(fread(buffer, 512, 1, image) == 1)
{ 

    //if a start of a jpeg is detected
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
    { 
        //if a jpeg is open close it 
        if (active == true)
        {
            fclose(imageNew);
            imageNew = NULL;
        }
        else
        { 
            active = true;
        }

        //title the new jpeg and open it. Also add to the img counter
        sprintf(filename, "%03i.jpg\n", images);
        imageNew = fopen(filename, "w");
        images++;

    }

    //if a jpeg is open write into it
    if (active == true)
    {
        fwrite(&buffer, 512, 1, imageNew);
    }
}

fclose(image);
if (imageNew != NULL) 
{ 
    fclose(imageNew);
}

return 0;

}

0

The first blocks of 512 bytes are zeros. You have to go through a few blocks and find the header of the first image. Then, you can start storing the data.

| improve this answer | |

You must log in to answer this question.

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