I just started on this code and for now I ONLY want to find the headers. Why doesnt this code find any? It seems to me it looks for blocks and then compares the first 4 bytes..

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

int main(int argc, char* argv[])
    if (argc != 1)
        printf("No arguments are taken for this program.\n");
        return 1;

    FILE* file = fopen("card.raw", "r");

    if (file == NULL)
        printf("Could not open file");
        return 2;

    uint8_t block[512];

    int count = 0;

        fread(block, 512, 1, file);

        if (block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] == 0xe0 || block[3] == 0xe1))
        printf("Found a jpeg header! count = %i\n", count);

    while (fread(block, sizeof(block), 1, file) == 1);


Let's assume that the missing } is a cut and paste typo and move on. ;-)

The problem is that you have TWO fread() calls. You are failing to process every other 512 byte block of code because it is read and then overwritten by the next read before being processed. It just happens that you all of the signatures are in the blocks that are overwritten. If you want to see for yourself, add a single fread() before the start of the do loop and run it. All of the signatures will be found.

The fread() call in the while() statement is not simply a test for EOF, it is actually executing a read!

Instead of a do/while, maybe you should do a simple while( fread() ) and process the blocks inside the loop, without any additional freads.

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

  • Thank you very much for this answer, I really didnt know the while() statement executed the fread() as well. that just saved my day! ps: and that missing } was indeed a copy paste mistake :) – Maurice Buiten Dec 8 '15 at 23:20

You must log in to answer this question.

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