【问题标题】:Fwrite to bitmap file causing infinite loopFwrite 到位图文件导致无限循环
【发布时间】: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
  • 您忽略了来自fopenfreadfwritefseek 的返回值!请把手放在电极上……
  • 你也是无条件返回EXIT_SUCCESS!

标签: c bitmap


【解决方案1】:

因为fwrite()fseek() 清除了EOF 标志,您将进入无限循环。你需要检查fread()是否成功,而不是检查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);
}

【讨论】:

  • 非常感谢,这是我第一次使用 C,我很困惑,但现在我明白了为什么。 gidnetwork.com/b-58.html 这也有帮助。
猜你喜欢
  • 2017-12-24
  • 2020-08-27
  • 2021-05-07
  • 2012-08-24
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多