0

My program won't end and I don't know why.

int counter = 0;
FILE* inptr = fopen("card.raw", "r");
BYTE compare[512];
fread(&compare, 512, 1, inptr);
while(!feof(inptr)) { 
    if ((compare[0] == 0xff) && (compare[1] == 0xd8) && (compare[2] == 0xff) && (compare[3] == 0xe0 || compare[3] == 0xe1)) {
        char filename[9];
        sprintf(filename, "%03d.jpg", counter);
        FILE* outptr = fopen(filename,"w");
        do {
            fwrite(&compare, 512, 1, outptr);
            fread(&compare, 512, 1, inptr);
        }
        while ((compare[0] != 0xff) || (compare[1] != 0xd8) || (compare[2] != 0xff) || (compare[3] != 0xe0 && compare[3] != 0xe1));      
        counter++;
        fclose(outptr);
    }
    else {
        fread(&compare, 512, 1, inptr);
    }
}



fclose(inptr);
return 0;

What is the quickest way I can fix this?

1

I don't know if it'll be quick....

I think you expect that this while while(!feof(inptr)) (the "outer while") will end when the fread in the "do/while"

     do {
        fwrite(&compare, 512, 1, outptr);
        fread(&compare, 512, 1, inptr);
        }
        while ((compare[0] != 0xff) || (compare[1] != 0xd8) ||......compare[3] != 0xe1));  

reaches end-of-file. It won't. I suspect your program has written out a really huge jpg as a result.

Be the computer. You are in the do/while. You read the last line in the file. It is not a jpg header, so the while is true. You do the "do" again, read another 512 bytes. It is not a jpg header, so the while is true. You do the "do" again, read another 512 bytes. Ad infinitum.

The first adjustment you have to make is in the outer while. Bottom line, !feof is not the proper way to test whether you have reached the end-of-file. See Week 4-> Shorts-> File I/0. Jason discusses this around the 8:15 mark. He's using fgets in the video, but it applies to fread. Obviously, that change is going to lead to other changes. I leave it to you to decide how to proceed.

:wq

You must log in to answer this question.

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