I am unsure on why my code is only recovering black and grey squares, instead of images. I have tried closing the file img in multiple places, and I still can't seem to solve the problem, I believe it is something I am missing logically. Any help would be greatly appreciated, here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
//define variables
const int BLOCK_SIZE = 512;
typedef uint8_t BYTE;
FILE *img;

int main(int argc, char *argv[])
   // declare and initialize variables
   int counter = 0;
   char filename[8];
    //define usage
    if(argc != 2)
        printf("Usage: ./recover IMAGE\n");
        return 1;

    // initislize variables
    BYTE buffer[BLOCK_SIZE];

     //open memory card
    FILE *f = fopen (argv[1], "r");
    // check if f exists
    if ( f == NULL)
      // exit program
      return 1;
    //read file
    while(fread(&buffer,  1, BLOCK_SIZE, f)==BLOCK_SIZE)
      //close previous file before writing

           //check 4 headers for jpeg
        if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
            //make new JPEG file
            sprintf(filename, "%03i.jpg", counter);
            //start writing to new file
            img = fopen(filename, "w");
              // incriment counter
              counter ++;
                 //write data to file
                 fwrite(&buffer, 1, BLOCK_SIZE, img);
         else if(img != NULL)
            fwrite(&buffer, 1, BLOCK_SIZE, img);
         //close files

    //return 0
     return 0;

1 Answer 1


Hmmm... did you check the sizes of the files that were created? Notice anything conspicuous?

Interesting that the files seem to only have the very top part of the image.

Questions: Where are the output files being closed? When processing the non-signature blocks that contain the rest of the image, is there an open output file? What happens when the code tries to write to a closed file pointer?

If this doesn't get you going, leave a comment.

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

You must log in to answer this question.

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