fseek() 越过文件限制但不终止
fseek() crossing file limit and not terminating
在最后一个 while 循环中,应该打印文件中存储的每第 5 个字符,但循环无限期地进行并且不会终止。
feof() 函数在到达 END OF FILE 时应该 return 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.
和fseek()
即使将位置指示器设置在EOF 之后也会成功。
因此很明显,当 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);
}
在最后一个 while 循环中,应该打印文件中存储的每第 5 个字符,但循环无限期地进行并且不会终止。 feof() 函数在到达 END OF FILE 时应该 return 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.
和fseek()
即使将位置指示器设置在EOF 之后也会成功。
因此很明显,当 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);
}