gpt4 book ai didi

c - Fwrite 到位图文件导致无限循环

转载 作者:行者123 更新时间:2023-11-30 16:35:55 34 4
gpt4 key购买 nike

我正在尝试用 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;
}

最佳答案

由于 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 - Fwrite 到位图文件导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48696364/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com