我做了一个程序来计算input.txt中的数字:
input.txt中
13 1 17 3 14 10 18 18 16 13 15 5 5 6 12 8 8 3 2 5 4 10 11 3 1 5 10 1 7 5 6 10 9 4 3 10 15 13
main.c中
#include<stdio.h>
int main()
{
FILE *fptr;
fptr=fopen("input.txt","r");
int data;
int count=0;
while(!feof(fptr))
{
fscanf(fptr,"%d",&data);
count++;
}
printf("%d",count);
}
结果是无限的字符'p'???
这有效:
#include <stdio.h>
int main(void) {
FILE *fptr;
if (!(fptr = fopen("input.txt", "r"))) {
printf("Could not open file\n");
return 1;
}
int data, count;
for (count = 0; fscanf(fptr, "%d ", &data) == 1; count++)
;
printf("%d\n", count);
fclose(fptr);
return 0;
}
请注意我对您的代码进行的以下调整。
while (!feof(fptr))
是不好的做法,往往不起作用。要检查文件中是否有剩余数据,请使用scanf()
语句本身作为循环条件。为了方便和高效,我做了一个for循环。fclose()
。这是绝对必要的,因为您不希望文件指针在内存中浮动,并且您希望系统/ shell知道该文件不再使用。int main()
应该在成功时返回0。如果你这样做,我可以认为你的编译器或二进制文件没有理由像这样打印“pppppp”。如果它继续这样做,则编译器或工作空间有问题。
以下提议的代码:
fclose()
来清理自己fopen()
和fscanf()
fscanf()
返回的值进行循环控制printf()
格式字符串,以便数据立即传递到终端,而不是等待程序退出。现在建议的代码:
#include <stdio.h> // fopen(), fclose(), fscanf(), perror(), printf()
#include <stdlib.h> // exit(), EXIT_FAILURE
int main( void )
{
FILE *fptr = fopen("input.txt","r");
if( ! fptr )
{
perror( "fopen failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
int data;
int count=0;
while( 1 == fscanf(fptr,"%d",&data) )
{
count++;
}
printf("%d\n",count);
fclose( fptr );
}