目录
文件结束判定
1.fgetc()函数返回EOF
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE* fp;
int count = 0;
if ((fp = fopen("test2.txt", "r")) == NULL)
{
printf("error\n");
system("pause");
return 0;
}
while (fgetc(fp) != EOF)
{
count++;
}
printf("%d\n", count);
system("pause");
return 0;
}
test.txt文件中又6个字符,所以也循环6次。
2.fgets()函数返回NULL
int main()
{
FILE* fp;
int i;
char str1[4];
char str2[4];
char str3[4];
char str4[4];
char* str[4] = { str1,str2,str3,str4 };
if ((fp = fopen("test2.txt", "r")) == NULL)
{
printf("error\n");
system("pause");
return 0;
}
for (i = 0; fgets(str[i], 4, fp) != NULL; ++i)
{
printf("str%d : %s\n", i + 1, str[i]);
}
printf("i = %d\n", i);
system("pause");
return 0;
}
可以看到10个字符,fgets函数一次读三个字符, 读了四次完成, 读到文件末尾返回NULL