0

My code creates the 50 files, all of them starting with the correct JPEG signature, however the rest of the bytes don't match up. In other words, first 4 bytes are correct, the following bytes are different. Also, when opening files it says Invalid or Unsupported Image Format. I've searched a lot and can't figure out what's wrong with my code logic. I would really appreciate some help.

typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    // Arguments check
    if (argc != 2)
    {
        printf("Usage: ./recover image");
        return 1;
    }

    // Open file
    FILE *file = fopen(argv[1], "r");

    int SIZE = 512;
    int file_count = -1;
    char *filename = NULL;
    FILE *img = NULL;
    int read = 0;

    // Read until end of file
    do
    {
      /*  if(file_count == 2)
        {
            break;
        }*/
        BYTE read_buffer[SIZE];
        read = fread(read_buffer, sizeof(BYTE), SIZE, file);

        // Check for empty buffer
        if (read == 0)
        {
            break;
        }

        // Check for JPEG
        if (read_buffer[0] == 0xff && read_buffer[1] == 0xd8 && read_buffer[2] == 0xff
                                 && (read_buffer[3] & 0xf0) == 0xe0)
        {
            if (img != NULL)
            {
                fclose(img);
            }

            filename = malloc(8);
            if (filename == NULL)
            {
                return 1;
            }

            file_count++;
            sprintf(filename, "%03i.jpg", file_count);
            img = fopen(filename, "w");
            free(filename);
        }

        if (img != NULL)
        {
            fwrite(read_buffer, sizeof(read), 1, img);
        }

    }
    while (read == SIZE);
    fclose(img);
    fclose(file);
}
0

Interesting fact: the output files are almost all less than 1000 bytes and none are the same size.

Look at the following:

        fwrite(read_buffer, sizeof(read), 1, img);

What is read? Isn't it an integer? If that's the case, then what is sizeof(read)? Try printing it out:

    printf("sizeof read = %lu \n", sizeof(read) );

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

1
  • Thanks for your help! It should be read, not sizeof(read) which is always 4 bytes. I don't know what was going through my head! Now works perfectly :) – Devplayer Dec 23 '20 at 11:17

You must log in to answer this question.

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