gpt4 book ai didi

c - fseek() 跨越文件限制并且不终止

转载 作者:行者123 更新时间:2023-11-30 20:04:10 27 4
gpt4 key购买 nike

在最后一个 while 循环中,应打印文件中存储的每 5 个字符,但循环无限期地进行并且不会终止。feof() 函数应该在到达 END OF FILE 时返回 1,并且应该退出循环,但循环会无限期地进行。

#include<stdio.h>

main() {
long n, k;
char c;
FILE *fp;
fp = fopen("RANDOM", "w");

while ((c = getchar()) != EOF) {
putc(c, fp);
}

n = ftell(fp);
printf("\nNo. of characters entered by the user is : %ld\n", n);
fclose(fp);
fp = fopen("RANDOM", "r");

while(feof(fp) == 0) {
n = ftell(fp);
c = getc(fp);
printf("The character at %ld position is %c\n", n, c);
fseek(fp, 4l, 1);
}
}

最佳答案

来自man fseek() :

A successful call to the fseek() function clears the end-of-file indicator for the stream.

即使您将位置指示器设置在 EOF 后面,fseek() 也会成功。因此很明显,当 fseek() 是循环中的最后一个命令时,while (feof(fp) == 0) 将永远不会终止。

相反,你可以这样做:

for( ;; ) {
n = ftell(fp);
if( (c = getc(fp)) == EOF )
break;
printf("The character at %ld position is %c\n", n, c);
fseek(fp, 4l, SEEK_CUR);
}

关于c - fseek() 跨越文件限制并且不终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43638871/

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