0

Stuck on this problem for days and I can't figure out why my code is failing, I'll admit I'm struggling to really understand what my code is doing, like how the filename variable works. But I've written this to the best of my ability based on what I learned in lecture and in the follow up videos. Yet, I still get these two failures :( recovers middle images correctly 001.jpg not found :( recovers 049.jpg correctly recovered image does not match.

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

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("Please include only a single name for a forensic image\n");
        return 1;
    }
    //creating a pointer where we can read the contents of the file we open
    FILE *fr = fopen(argv[1], "r");

    if (fr == NULL)
    {
        printf("This program cannot be opened for reading\n");
        return 1;
    }
    unsigned char buffer[512];
    char filename[8];
    int counter = 0;
    FILE *img;
    //blocks are 512 bytes so we can just check that many before moving on
    //size of each element here is 512

    while(fread(buffer,sizeof(buffer),1,fr) > 0)
    {

        if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if(counter == 0)//very first jpeg
            {
                sprintf(filename, "%03i.jpg",counter);
                img = fopen(filename, "w");
                fwrite(buffer, sizeof(buffer),1, img);
                counter++;
            }
            else//must be a new jpeg if we got a new match
            {
                fclose(img);
                counter++;
                //name a new file
                sprintf(filename, "%03i.jpg",counter);
                //open that file to write in
                img = fopen(filename, "w");
                fwrite(buffer, sizeof(buffer),1, img);
            }
            }
        else//same picture so keep writing
        {
            fwrite(buffer, sizeof(buffer),1, img);
        }
    }
    fclose(img);
    fclose(fr);
    return 0;
}
0

You might want to standardise where your counter++ appears, before sprintf(filename, "%03i.jpg",counter) or after? From your code, the jpeg file names will skip over 001.jpg.

| improve this answer | |

You must log in to answer this question.

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