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

typedef uint8_t BYTE;

int check_jpg(BYTE array[]);

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        printf("Usage:./recover image\n");
        return 1;
    }
    FILE *file = fopen(argv[1], "r");
    if(file == NULL)
    {
        fclose(file);
        printf("Could not open %s. \n", argv[1]);
        return 1;
    }
    BYTE bytes[512];
    int count = 0;
    char number[50];
    do{
         fread(bytes, 512, 1, file);
      }
    while(check_jpg(bytes) == 0);
    while(!feof(file))
    {        
        if(count<10)
        {
            sprintf(number, "00%i.jpg", count);
        }
        if(count>=10)
        {
            sprintf(number, "0%i.jpg", count);
        }
        FILE *final = fopen(number, "w");
        fwrite(bytes, 512, 1, final);
        fread(bytes, 512, 1, file);
        while(check_jpg(bytes) == 0)
        {        
           fwrite(bytes, 512, 1, final);
           fread(bytes, 512, 1, file);
        }
        count++;
        if(count>49 || feof(file))
        {
           break;
        }
        fclose(final);
    }
    fclose(file);
    return 0;
}

int check_jpg(BYTE array[])
{
    if(array[0] == 0xff && array[1] == 0xd8 && array[2] == 0xff && (array[3] & 0xf0) == 0xe0)
    {
        return 5;
    }
    else
    {
        return 0;
    }
}
1

Actually, it's not working correctly. There's an infinite loop. It may look like it's working fine on your IDE, but try checking the file size of 049.jpg. It's growing without bound. I suspect your IDE is terminating the program when the disk space is being used up.

Take a close look at the code related to handling the EOF for the input file.

Here's another hint. When code is duplicated, it's a red flag that the code can be simplified.

Happy coding! ;-)

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

1
  • Thanks a lot! It works perfectly now. Mar 22 at 9:59

You must log in to answer this question.

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