0

I am trying to write an image color inverter for bitmap files in C. I looked at the similar question here but none of the answers worked. infinite loop in while loop

Here is my the while loop that gets stuck:

while(!feof(f))
{
    //stride = 4 * ((width * bytesPerPixel + 3) / 4);
    fread(&pix, sizeof(struct pixel),1, f); // put pixels into struct

    pix.blue = ~pix.blue;
    pix.green = ~pix.green;
    pix.red = ~pix.red;

    fseek(f, -sizeof(struct pixel) , SEEK_CUR);
    fwrite(&pix, sizeof(struct pixel),1, f);
    fseek(f, 0, SEEK_CUR);
}

Here is the rest of my code:

int main(){
FILE *f;

f = fopen("penguin.bmp", "rb+");

struct bmp_header bmphead;
fread(&bmphead, sizeof(struct bmp_header), 1, f);

struct dib_header dibhead;
fread(&dibhead, sizeof(struct dib_header), 1, f);

if (dibhead.size != 40 || dibhead.bpp != 24){
    printf("Error. File format not supported.");
    return EXIT_FAILURE;
}

fseek(f, bmphead.offset, SEEK_SET); // Get to start of pixels
struct pixel pix;
while(!feof(f))
{
    //stride = 4 * ((width * bytesPerPixel + 3) / 4);
    fread(&pix, sizeof(struct pixel),1, f); // put pixels into struct

    pix.blue = ~pix.blue;
    pix.green = ~pix.green;
    pix.red = ~pix.red;

    fseek(f, -sizeof(struct pixel) , SEEK_CUR);
    fwrite(&pix, sizeof(struct pixel),1, f);
    fseek(f, 0, SEEK_CUR);
}

fclose(f);
return EXIT_SUCCESS;
}

1 Answers1

0

You're getting an infinite loop because the fwrite() and fseek() clear the EOF flag. You need to check whether the fread() succeeds instead of checking feof(f).

while (fread(&pix, sizeof(struct pixel),1, f)) {
    pix.blue = ~pix.blue;
    pix.green = ~pix.green;
    pix.red = ~pix.red;

    fseek(f, -sizeof(struct pixel) , SEEK_CUR);
    fwrite(&pix, sizeof(struct pixel),1, f);
    fseek(f, 0, SEEK_CUR);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • thank you so much, its my first time working with C and I was confused but I understand why now. http://www.gidnetwork.com/b-58.html this helped as well. – Farhan Farooqui Feb 09 '18 at 04:41