0

I dont get why all of my jpeg's appear but they are all invalid. When i try to open them none of them opens and gives "invalid or unsupported Image format" error.Can someone help me to spot what am i doing wrong ? Here's my code :

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

int main(void){

    FILE* infile = fopen("card.raw","r");
    if(infile == NULL){
        printf("Could not load the memory card");
        return 1;
    }
    unsigned char memory[512] = {0};

    // array for filename is 8 for "000.jpg"
    char jpgName[7];
    int jpgcounter = 0;
    FILE* outfile = NULL;

    while(fread(memory,sizeof(memory),1,infile) == 1){
        if(memory[0] == 0xff && memory[1] == 0xd8 && memory[2] == 0xff && (memory[3]>=0xe0 || memory[3]<=0xef)){
            if(outfile != NULL){
                fclose(outfile);
            }
            sprintf(jpgName,"%0.3d.jpg",jpgcounter);
            outfile = fopen(jpgName,"a");
            fwrite(memory,sizeof(memory),1,outfile);
            jpgcounter++;
        }
        else{
            if(outfile != NULL){
                fwrite(memory,sizeof(memory),1,outfile);
            }
        }
    }
    fclose(infile);
    fclose(outfile);
}

1 Answer 1

4

It's a subtle problem and a common error for this assignment. The first byte of the first block of data is being overwritten before it is being written out to the file. This corrupts the jpeg signature and causes the error that you see.

The cause of the overwrite lies in the file name creation. When the code builds the file name, it stores it in jpgName. The file name is 7 chars long, 3 digits, a dot, and 3 letters. But, that's not the end of it. This string still requires a string terminator, \0, making a length needed of 8.

    char jpgName[7];

So, when the code creates a filename, it writes 8 characters, including the \0. That end of string marker gets written to the first byte of whatever memory follows jpgName, which happens to be memory[0], thus corrupting the signature after it has been detected, but before it is written to the output file.

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

4
  • Thanks for pointing out the mistake Cliff. My program is working correctly now !! I spent hours on finding out the bug but couldn't find it. Now i feel so stupid having read about the mistake haha. Thanks again !! Nov 27, 2016 at 12:36
  • Ditto, Akshay! Thank you, Cliff B!! Dec 11, 2016 at 9:28
  • Thank you Cliff B. To be honest, I would have thought this was the last thing causing me an issue. I would have assumed errors in more core areas. But thank you, this just fixed my program so I now pass all tests. :) May 28, 2017 at 22:03
  • Well, I did say that it was both subtle and common. ;-)
    – Cliff B
    May 29, 2017 at 1:12

You must log in to answer this question.

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