gpt4 book ai didi

c - 读取文件时无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 02:14:36 25 4
gpt4 key购买 nike

我正在使用此函数进行无限循环(在 while 循环中)。我是处理文件的新手,所以我觉得我遗漏了什么...我看不出哪里出了问题。

void cipher(FILE* password_ptr,int n)
{
if (password_ptr == NULL)
{
printf("Error:password_ptr points to null");
return;
}
while(!feof(password_ptr))
{
fseek(password_ptr, 0, SEEK_CUR); // don't move
int en=fgetc(password_ptr)+n;

fseek(password_ptr, -1, SEEK_CUR); // move backwards one character
if(fputc(en,password_ptr)!=en)
{
printf("Error:fputc didn't work");
}
fseek(password_ptr, 0, SEEK_CUR);
}
fclose(password_ptr);
};

谢谢!

最佳答案

调用 fseek() 的副作用是文件上的 EOF 指示被清除:

C99 7.19.9.2/5 fseek 函数:

After determining the new position, a successful call to the fseek function undoes any effects of the ungetc function on the stream, clears the end-of-file indicator for the stream, and then establishes the new position.

请注意,您的代码还使用了由 feof() 函数控制的循环的常见反模式。该函数不会返回 EOF,直到 I/O 操作将您带到那个点(设置文件结束指示符)。换句话说,即使您进入循环,fgetc() 也可能由于位于文件末尾而失败(这将设置文件末尾指示符)。但是随后的搜索将清除该指示器。同时,您将对 EOF 进行操作,就好像它是正常的、成功的读取一样。

参见:

您可能想尝试以下循环:

int c;
while((c = fgetc(password_ptr)) != EOF)
{
int en= c+n;

fseek(password_ptr, -1, SEEK_CUR); // move backwards one character
if(fputc(en,password_ptr)!=en)
{
printf("Error:fputc didn't work");
break;
}
}

您还需要考虑您希望这段代码如何处理 en 超出 unsigned char 范围的情况。由于 fputc() 在将其写入流之前将要写入的字符转换为 unsigned char,如果 en 超出该范围将显示“fputc didn't work”错误。例如,如果将 n 添加到 fgetc() 读取的字符大于 255,则可能会发生这种情况。

关于c - 读取文件时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9552150/

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