0

include

include

int main(void) { FILE* file = fopen("card.raw", "r");

int* data = malloc(513);

if(data == NULL)
{
    printf("failed to do task\n");
    return 1;
}
else
{
    int k = 0;

    int count = 0;
    int count2 = 0;
    int count3 = 0;
    char* name = malloc(50);
    FILE* out_data;

    while(fread(data , 512 , 1 ,file) > 1)
    {

        if(data[0] == 0xff && data[1] == 0xd8 && data[2] == 0xff && ( data[3] == 0xe0 || data[3] == 0xe1 ))
        {
            sprintf(name,"%d%d%d",count3,count2,count);
            if(k > 0)
            {
                fclose(out_data);
            }

            out_data = fopen("name.jpg","w");
            fwrite(data , 512 , 1 , out_data);

            k++;

            count++;
            if(count == 9)
            {
                count = 0;
                count2 = count2 + 1;
            }

        }
        else if(data[0] != 0xff || data[1] != 0xd8 || data[2] != 0xff || ( data[3] != 0xe0 || data[3] != 0xe1 ))
        {
            fwrite(data , 512 , 1 , out_data);
        }
    }


    free(data);
    free(name);
    fclose(file);
    return 0;
}

}

1

Using int array as a buffer storage is incorrect. Try unsigned char buffer[512]; instead?

For if (data == NULL) line, I think you meant to check presence of card.raw file, not the buffer itself. Take a look at previous problems. Same for name variable, you can allocate it statically (and even less space). Don't forget that stack memory mustn't be freed, though.

Your while loop won't execute. fread() will only return 0 and 1 in your case. Please refer to the documentation for more information.

I'm not sure about your if condition. See this. It asks you to check wider range of file headers. (Your program, after fixing everything else, still works properly nevertheless.)

The name variable becomes useless even if you do sprintf() on it. Line out_data = fopen("name.jpg", "w"); has to make use of it.

After fixing these, your program can recover all the pictures. However, there are still problems with file name. All names ending with 9.jpg are skipped. I'll leave that to you. (It's actually possible to use only one count variable.)

Taking care of these things should make your program works properly. Good luck. Have fun!

1
  • I have got my problem it was with else if and i have solved it thanks for your help – Karan Garg Apr 3 '16 at 14:49

You must log in to answer this question.

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