0

I know that there are many other issues with my code, but I cannot seem to understand why only 49 images are recovered. Also, it would be great to get any pointers to why all of the recovered are blank.

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

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Can only accept one input value\n");
        return 1;
    }

    char *raw_image = argv[1];

    // open input file
    FILE *inptr = fopen(raw_image, "r");
    if (inptr == NULL)
    {
        fclose(inptr);
        fprintf(stderr, "Could not open %s.\n", raw_image);
        return 2;
    }

    // keep count of JPEGs
    int jpegCounter = 0;

    unsigned char block[512];

    // filename array can hold any value
    char filename[10];

    FILE *img = NULL;

    while (1)
    {
        fread(&block, 512, 1, inptr);

        // on end of the file terminate program
        if (feof(inptr))
        {
            fclose(inptr);
            fclose(img);
            return 0;
        }

        // identify the the first set of bytes in the JPEG
        if (block[0] == 0xff &&
            block[1] == 0xd8 &&
            block[2] == 0xff &&
            (block[3] & 0xf0) == 0xe0)
        {
            sprintf(filename, "%03i.jpg", jpegCounter);

            // open found JPEG
            img = fopen(filename, "w");
            fwrite(&block, 512, 1, img);
        }

        // check for the beginning of the new JPEG
        if (block[0] == 0xff &&
            block[1] == 0xd8 &&
            block[2] == 0xff &&
            (block[3] & 0xf0) == 0xe0)
        {
            // increase the count of JPEGs
            jpegCounter++;

            // close first image
            fclose(img);
        }
    }

    // close infile
    fclose(inptr);

    // success
    return 0;
}

0

Ummm... your code recovers 50 files. Remember, the first file is named 000.jpg, not 001.

Next, have you looked at the file size of all the created image files? ls -al *.jpg

Every file is 512 bytes. That tells me that every 512 byte data block is being discarded. Image files are not limited to 512 bytes. Once the first data block with a signature is found, every data block that follows is part of the same file, until the next signature is found, and must be added to the image file. The code isn't processing data blocks without signatures.

As a side note, the code has two if statements/code blocks to check for signatures. The second one is redundant. All of the actions can be done in a single if block.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • You're right, I was looking for 050.jpg, which would make 51 images instead of 50. Thank you for your pointers, I will continue working. – alljamin Sep 22 '19 at 11:04

You must log in to answer this question.

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