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;
}
4
  • 3
    why while (!feof(file)) is wrong Commented Feb 8, 2018 at 23:17
  • I get that but what's the alternative... I cannot test a read or write as that will mess with where the file pointer is @barmar Commented Feb 8, 2018 at 23:50
  • 1
    You are ignoring return values from fopen, fread, fwrite and fseek! Please place your hands on the electrodes... Commented Feb 8, 2018 at 23:55
  • You are also unconditionally returning EXIT_SUCCESS! Commented Feb 8, 2018 at 23:59

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much, its my first time working with C and I was confused but I understand why now. gidnetwork.com/b-58.html this helped as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.