2

My code compiles and runs without any errors. Images are generated, but the images are incomplete, here's an example of 000.jpg: https://i.imgur.com/Ovs2Xv8.png. I can't really find what's wrong in my code, any help is appreciated!

#include <string.h>
#include <stdio.h>

int main (int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: recover <raw_file>\n");
        return 1;
    }

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

    int jpegsFound = 0;
    unsigned char buffer[512];
    FILE *img;

    while (fread(&buffer, 1, 512, inptr) == 512)
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            // Block consists header of a new jpeg file

            if (jpegsFound > 0)
            {
                // Already found image, should close now
                fclose(img);
            }

            jpegsFound++;

            // Now handle the new file
            char filename[8]; // 000.jpg\0

            sprintf(filename, "%03i.jpg", jpegsFound - 1); // Start from 000.jpg

            img = fopen(filename, "w");
            if (img == NULL)
            {
                fclose(img);
                fprintf(stderr, "Could not create %s.\n", filename);
                return 3;
            }

            fwrite(&buffer, sizeof(buffer), 1, img);
        }

        if (jpegsFound > 0)
        {
            // A continued data of the last image
            fwrite(&buffer, sizeof(buffer), 1, img);
        }

        // Clears the buffer
        memset(&buffer, 0, 512);
    }

    fclose(inptr);
    fclose(img);

    return 0;
}
4

if (jpegsFound > -1)

Shouldn't that be an else if?

Your current code says:

read in 512 bytes
   if it's a signature
      close file (if open)
      open new file
      increment counter
      write 512 bytes
   if I've found a jpg previously
      write 512 bytes

that second if will write the signature block to the file (again).

Also, no need to clear the buffer. It will be overwritten by the next fread.

  • Thanks for helping out! It worked perfectly. Should have found the issue earlier. – Birkhoff Lee Jul 31 '18 at 3:56
4

I agree with Brenda's answer above. But also, you're initialising jpegsFound to 0. That's the value it will have before any signatures were found. Are you sure you want to write to the file when jpegsFound > -1 ?

  • Looks like he edited his code after we looked at it. – curiouskiwi Jul 31 '18 at 3:54
  • Yes - thanks for looking into the code tho! :) – Birkhoff Lee Jul 31 '18 at 3:56

You must log in to answer this question.

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