0

Here's my code:

int main(int argc, char* argv[])
{
    FILE* card = fopen("card.raw", "r");
    if (card == NULL)
    {
        printf ("File doesn't exist");
        return 1;
    }

    uint8_t cardMemo[512];

    if (cardMemo == 0)
    {
        printf ("Out of Memory");
        return 2;
    }
    int t = 0;
    FILE* image = NULL;
    while (fread(&cardMemo, 512, 1, card) == 1)
    {  
        if (cardMemo[0] == 0xff && cardMemo[1] == 0xd8 && cardMemo[2] == 0xff && (cardMemo[3] == 0xe0 || cardMemo[3] == 0xe0))
        {
            //close previous image, if any
            if (image != NULL)            
                fclose(image);

            //setting for title
            char title[8];

            if (t<10)
            sprintf (title, "00%i.jpg", t);

            else if (t>=10)
            sprintf (title, "0%i.jpg", t);
            //create JPG
            image = fopen(title, "a");
            fwrite(&cardMemo, 512, 1, image);

            t++;
        }

        else
        {
            if (image != NULL)
            fwrite(&cardMemo, 512, 1, image);
        }
    }
fclose(image);
}
1
  • feof tests whether the EOF was already reached not whether the next thing to reach is the EOF. see What is the difference in behavior between fread and feof?

  • you don't need to keep track of the location of the file position indicator. all you need to do is to read the data block by block, check whether the first 4 bytes of a block are a JPG signature, and behave accordingly.

  • you are shadowing the variable called image inside your loop and this is probably the main cause of the segmentation fault.

4
  • Let's say I got 1 IF to check for the signature, in there lies create JPG, close previous if any, and fwrite, but how can I write data to that file? Because if I have some kind of condition to check- if the data don't have signature => write to the opening file- inside the IF statement above, the condition in the first IF is false and it got skipped. And if I write it outside in a ESLE, I can't access to the opening file due to different scope, and it's would be trying to write the data before the signature. And I got a SEG at the IF, I changed the shadowing, but it didn't even get that far
    – kenlenney
    Dec 21 '15 at 16:28
  • Thanks to your link and suggest, I've made some changes to my codes and it finally printing out some jpg, but only 13 pics were printed =.= I've edit the code above, it's been hours and I couldn't find what went wrong, please take a look and help again, thank you.
    – kenlenney
    Dec 22 '15 at 7:48
  • @kenlenney you may edit the original question and add the updated code!
    – kzidane
    Dec 22 '15 at 7:51
  • I figured it out, thank you :))
    – kenlenney
    Dec 23 '15 at 8:40

You must log in to answer this question.

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