Below is my code. It doesn't even compile, because I get the following error:

"passing 'unsigned char [512]' to parameter of type 'char *' converts between pointers to integer types with different sign"

 * recover.c
 * Computer Science 50
 * Problem Set 4
 * Recovers JPEGs from a forensic image.

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

int main(int argc, char* argv[])
    //Open the file
    FILE* inp = fopen("card.raw", "r");

    //Check if the file exists and can be opened
    if (inp == NULL)
    printf("Could not open 'card.raw'.\n");
    return 1;

//Declare the buffer where the block of 512 bytes will be stored
unsigned char buffer[512];

//Read from the file until it ends
while (fgets(buffer, sizeof(buffer), inp) != NULL)
    fread(&buffer, sizeof(buffer), 1, inp);

    //const char mark_1[4] =
    if  (buffer[0] == 0xff &&
         buffer[1] == 0xd8 &&
         buffer[2] == 0xff &&
         buffer[3] == 0xe0)
        printf("found \n");

        printf("not found \n");
    // when found, start at the beginning of the block and write it

    //when we hit it, every block has to be written to a new jpeg file (so write)

    //when we hit the next block, we close the last jpeg and start writing to a new jpeg file

    //sprintf(char title[8], "%.3d.jpg", 2)
    //title: char array to store the resultant string

    //this prints out 2.jpg and not 002.jpg (NOT ANYMORE)


Help would be appreciated!

1 Answer 1


There are two problems. First, you're doing a double read. Why do you have an fgets() call followed immediately by an fread() call? The fgets is throwing the error. Replace it with the single fread.

Next, your code will either find or not find the signature on the first 512 block. BUT, because of the break; lines, it immediately exits the while loop, so you never read a second one.

If you want to do something more interesting, like see how far you have to run to get to a signature, comment out the break on the not found side and add a counter that increments by 1 on each pass there. When you find the first signature, the break will cause the program to exit the loop and the program will complete. If you print the counter value in the found code before the break there, it will tell you how many 512 byte blocks that you have to read to get to the signature. ;-)

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

  • Thank you very much. I was wondering why it never found anything!
    – JuM24
    Nov 14, 2015 at 17:55

You must log in to answer this question.

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