用fscanf()从文件取数据时,如何判断文件结束

例子:从键盘输入若干行字符(每行长度不等),输入后把它们存储到一磁盘文件中。再从该文件中读入这些数据,将其中小写字母转换成大写字母后再显示屏上输出。

有两种方法

1.使用feof()函数

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 
 5 int main(){
 6     setbuf(stdout,NULL);
 7     char s[20];
 8     char choice='y';
 9     FILE *fp;
10 
11     if((fp=fopen("string.txt","w+"))==NULL)
12     {
13         printf("cannot open the file.
");
14         exit(0);
15     }
16 
17     while(choice=='y')
18     {
19         printf("Input a line:
");
20         gets(s);
21         fprintf(fp,"%s
",s);
22         printf("Again?");
23         scanf("%c",&choice);
24         fflush(stdin);
25     }
26 
27     printf("print the data in the file.
");
28     rewind(fp);
29     fscanf(fp,"%s",s);
30     while(!feof(fp))
31     {
32         puts(strupr(s));
33         fscanf(fp,"%s",s);
34     }
35     fclose(fp);
36     return 0;
37 }

2.使用文件结束符EOF

1 while(fscanf(fp,"%s",s)!=EOF)
2 {
3     puts(strupr(s));
4 }
原文地址:https://www.cnblogs.com/Camilo/p/3381956.html