0

I'm stuck in Recover. I've been trying for two days. Now my code opens 49 images but they are "Invalid or Unsupported Image Format. I can't identify where I'm going wrong, please help me.

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

typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    // Checks the number of command-line arguments
    if (argc != 2)
    {
        return 1;
    }
    // Open input file
    char *nameFile = argv[1];
    FILE *file = fopen(nameFile , "r");
    FILE *img = NULL;

    if (file == NULL)
    {
        return 1;
    }

    int imageNumber = 0;
    BYTE buffer[512];
    char filename[6];

    while (fread(buffer, sizeof(buffer), 1, file) == 1)
    {
        if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] >= 0xe0 && buffer[3] < 0xf0))
        {
             sprintf(filename, "%03i.jpg", imageNumber);
             if (imageNumber == 0)
             {
                img = fopen(filename, "w");
             }
             else
             {
                fclose(img);
                img = fopen(filename, "w");
             }
             imageNumber++;
        }
        if (imageNumber > 0)
        {
            fwrite(buffer, 512, 1, img);
        }
    }
    return 0;
}

1 Answer 1

0

It's a subtle problem, having to do with memory. If you look, filename only has space allocated for 6 chars. It needs 8 - 7 for the full name of the file plus the end of string marker.

When insufficient space is allocated, in this case, 6, and more space (8) is needed, the code will go ahead and overwrite the next two bytes in memory to store the full file name. It's common in this pset that the next physical memory is the buffer. So, the first two bytes of the buffer get overwritten when a new file is opened. Since these two bytes are part of the signature block for the image file, they're corrupted and when any image reader code tries to display the file, they don't recognize the file as a valid image.

Try allocating the correct amount of space for the filename string.

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

1
  • It's works! Thank you! May 30, 2020 at 21:46

You must log in to answer this question.

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