0

So I've made progress and wrote what I have in here. My program outputs 50 jpegs of size 512 bytes. I know that may program writes only 512 bytes to a newly created jpeg but I don't know what should I do afterwards and write enough bytes into the jpeg?

Here's my code:

/**
 * recover.c
 *
 * Computer Science 50
 * Problem Set 4
 *
 * Recovers JPEGs from a forensic image.
 */
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <stdint.h>
#include <string.h>

typedef uint8_t  BYTE;

int main(int argc, char* argv[])
{
    FILE* card = fopen("card.raw", "r");

    if (card == NULL)
    {
        printf("Could not open %s.\n", "card");
        return 2;
    }


    //Correct values for the first four bytes.
    BYTE crct1[4] = {0xff, 0xd8, 0xff, 0xe0};
    BYTE crct2[4] = {0xff, 0xd8, 0xff, 0xe1};

    //The buffer, containing an array with elements of size 1 Byte.
    BYTE buf[512];

    //Jpg count
    int imgcount = 0;
    //Image name
    char imgname[8];
    //Output pictures. Setting it to NULL because it can point to something which might cause a bug.
    FILE* outimg = NULL;

    //Checks and reads the card to the buffer unless its the EOF.
    while (fread(buf, 512, 1, card) == 1)
    {


        if (buf[0] == crct1[0] && buf[1] == crct1[1] && buf[2] == crct1[2] && (buf[3] == crct1[3] || buf[3] == crct2[3]))
        {

            //Closing the file, if one is opened already.
            if (outimg != NULL)
            {
                fclose(outimg);
            }
            //Naming the file.
            sprintf(imgname, "%03d.jpg", imgcount);

            //Making a new image file pointer to write the bytes too.
            outimg = fopen(imgname, "w");

            fwrite(buf, 512, 1, outimg);

            imgcount++;
        }

    }

    fclose(card);
    fclose(outimg);

}
1

According to your code's logic, a new file will be opened and be written with 512 KB data each time it finds the specific header. Your program won't write any other 512 KB chunks to the file because the condition isn't satisfied. It simply skips until a new file is opened. Try tweaking a bit.

Also, you're only checking two headers: 0xff, 0xd8, 0xff, 0xe0 and 0xff, 0xd8, 0xff, 0xe1. There are more possibilities. Please see specifications.

1
  • Thanks, solved if finally!!!
    – yousafe007
    Mar 28 '16 at 22:51

You must log in to answer this question.

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