0

My program is compiling properly it is even recovering the images but when I am opening the image to view, it is not opening. It is showing "Invalid or Unsupported file format". Please look into it. Here is my code:

#include <stdio.h>

#include <stdlib.h>

#include <stdint.h>

typedef uint8_t BYTE;

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

    FILE *card = fopen(argv[1], "r");
    if (card == NULL)
    {
        printf("Could not open card.\n");
        return 1;
    }

    FILE *new_card;// = fopen(argv[1], "w");

    unsigned char header[512];

    //BYTE header[512];
    char *name = malloc(8 * 512);
    int img_count = 0;
    fread(&header, 512, 1, card);

    // checking for if end of data on card has reached.
    if(feof(card))
    {
        printf("Testing EOF\n");
    }


    while (fread(&header, 512, 1, card) == 1)
    {
        if (header[0] == 0xff && header[1] == 0xd8 && header[2] == 0xff && (header[3] & 0xf0) == 0xe0)
        {    
            if(new_card != NULL)
            {
                fclose(new_card);
            }
                sprintf(name, "%03i.jpg", img_count);
                new_card = fopen(name, "w");
                img_count++;
        }
         if(new_card != NULL)
        {
            fwrite(header, 512, 512, new_card);
        }
    }

    free(name);
    fclose(card);
    fclose(new_card);

}

1 Answer 1

2

Suspect a problem here fwrite(header, 512, 512, new_card);. Program is writing 512 * 512 bytes. Double check the arguments with man fwrite.

5
  • Beat me by seconds! Kudos. Also, the code allocates 8 * 512 for name to hold an 8 byte file name. Thats a waste of memory.
    – Cliff B
    Jun 16, 2021 at 21:09
  • Thanks for the reply. I didn't understand, will appreciate if you could elaborate the solution or provide me the details where code changes are needed. Jun 20, 2021 at 17:23
  • header is allocated for 512 bytes and reads 512 bytes, then fwrite is writing 512*512 , or 262,144 bytes. It should only write 512 bytes. Jun 21, 2021 at 11:55
  • So can you suggest on what should I do? Cause according to me I don't think fwrite is multiplying 512 into 512. I think that 512 is the size of the elements it is suppose to write. Jun 24, 2021 at 16:51
  • If you want to write one 512-byte block the syntax is fwrite(header, 512, 1, new_card); Jun 25, 2021 at 10:57

You must log in to answer this question.

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