【发布时间】:2018-02-08 23:16:47
【问题描述】:
我正在尝试为 C 中的位图文件编写图像颜色转换器。我在这里查看了类似的问题,但没有一个答案有效。 infinite loop in while loop
这是我卡住的while循环:
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);
}
这是我的其余代码:
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;
}
【问题讨论】:
-
我明白了,但有什么替代方法...我无法测试读取或写入,因为这会混淆文件指针的位置@barmar
-
您忽略了来自
fopen、fread、fwrite和fseek的返回值!请把手放在电极上…… -
你也是无条件返回EXIT_SUCCESS!