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

typedef uint8_t  BYTE;

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

//declare buffer variable
BYTE chunk[512];

int ctr = 0;
char title[8];

//check for end of file
while(fread(&chunk, sizeof(chunk), 1, file) != 0)
{
    fseek(file, -(sizeof(chunk)), SEEK_CUR);
    // search for beginning of jpg
    while(!(chunk[0]==0xff && chunk[1]==0xd8 && chunk[2]==0xff && (chunk[3] >= 0xe0) && (chunk[3] <= 0xef)))
    {
        fread(&chunk, 512, 1, file);
    }

    if(ctr<10)
    {
        sprintf(title, "00%d.jpg", ctr);
    }
    else
    {
        sprintf(title, "0%d.jpg", ctr);
    }

    FILE* img = fopen(title, "w");

    fwrite(&chunk, 512, 1, img);
    fread(&chunk, 512, 1, file);

    while(!(chunk[0]==0xff && chunk[1]==0xd8 && chunk[2]==0xff && (chunk[3] >= 0xe0) && (chunk[3] <= 0xef)))
    {
        fwrite(&chunk, 512, 1, img);
        if(fread(&chunk, 512, 1, file) != 1)
        {
            fwrite(&chunk, 512, 1, img);
            break;
        }
    }
    ctr++;
    fclose(img);
}

fclose(file);
return 0;
}

Maybe it's not the most organized code, but from what I see it's supposed to work. I ran it through the gdb and it iterates through the loops like it it should. It recovers half of the images correctly, but then freezes on the 24th and has to be forced to quit.

1 Answer 1

2

When the code is reading data blocks and writing to an output file, it is looking for a new signature. When it finds one, it exits the loop and goes back up to the top of the outer while loop and reads the next data block without opening a new file for the signature that it just found. Because of this, it skips data until it finds the next signature. In short, it is skipping every other file.

The infinite loop happens because the freads inside the inner loop don't deal with EOF at all, so the last read block in the file gets recycled over and over. Also, remember that when the last image file is being processed, there will not be another signature block.

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 .