0

Struggling with recover at this moment. My code creates just 8 pictures out of 50 - from 2nd to 9th. Other jpegs are also made but i am unable to see them due to "Invalid or Unsupported Image Format". My code is below. Would be grateful for any help!

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

typedef uint8_t BYTE;

int main(int argc, char *argv[])
{

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

    char *infile = argv[1];

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

    BYTE buffer[512];

    char filename[8];

    int jpgcounter = 0;

    FILE *img = NULL;

    while(fread(&buffer, 512, 1, inptr) == 1)
    {
        if ((buffer[0] == 0xff &&
            buffer[1] == 0xd8 &&
            buffer[2] == 0xff &&
            (buffer[3] & 0xf0) == 0xe0) || img == NULL)
        {
            if(img != NULL)
            {
                fclose(img);
                img = NULL;
            }

            sprintf(filename, "00%i.jpg", jpgcounter);
            img = fopen(filename, "w");

            if(img == NULL)
            {
                fprintf(stderr, "Could not open %s.\n", filename);
                return 4;
            }
            jpgcounter++;
        }
        if (img != NULL)
            fwrite(&buffer, 512, 1, img);
    } 

    if(img != NULL)
        fclose(img);

    if(inptr != NULL)
        fclose(inptr);

    return 0;
}

1 Answer 1

0

I would say that the two main problems are found in the following statements:

  sprintf(filename, "00%i.jpg", jpgcounter);
  img = fopen(filename, "w");

The format for sprintf should be

"%03d.jpg"

Regarding fopen the "w" mode says the following: "Creates an empty file for writing. If a file with the same name already exists, its content is erased and the file is considered as a new empty file."

That is, the previous content is erased, you must review the fopen () documentation, and find another way to open the file other than "w". I hope it serves to continue.

4
  • Thank you very much for advice. I've done directly as you told me and now I have all images recovered from 001.jpg to 050.jpg. But I still can't open very first jpeg and my code doesn't pass check50. Any other thoughts?cs50.me/checks/7c50cbc738be5f215bc352467e8d48a3702a21ac
    – Viapacific
    Commented Jun 25, 2019 at 5:45
  • (buffer[3] & 0xf0) == 0xe0) || img == NULL). I do not understand what img == NULL does, I'm almost sure that this will give you false positives
    – MARS
    Commented Jun 25, 2019 at 12:02
  • Thank you very much! It worked out!
    – Viapacific
    Commented Jun 25, 2019 at 20:02
  • Glad to hear it, Onward!
    – MARS
    Commented Jun 25, 2019 at 20:09

You must log in to answer this question.

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