I wrote some quick code that is supposed to invert colors of a BMP image. I test with a 40x40 dimensional BMP image, created by paint. However the function seem to fill it e
Adding an fseek into the loop fixes it, although I don't understand why:
for (i = 54; i != 54 + raw_data; i++) // <=
{
fseek(fp, i, SEEK_SET);
int old = fgetc(fp);
fseek(fp, i, SEEK_SET);
fputc(255 - old, fp);
}
In trying to figure out the problem, I did this, to see if the position in the stream was correct:
for (i = 54; i != 54 + raw_data; i++) // <=
{
long x = ftell(fp);
printf("%d,", x);
int old = fgetc(fp);
fseek(fp, i, SEEK_SET);
fputc(255 - old, fp);
}
And indeed it is. It ouputs 54,55,56,57,... so the fseek() should not be necessary! But if you look at the result of the fgetc(), the "old" value always seems to be reading the pixel at 54. I think @RSahu was correct: don't read and write like that to one file. Better to read the data into a buffer, then negate the buffer, then write it to disk. Or write to a different file entirely.
Maybe this has to do with buffering?