数据文件——之读取文本文件中的结构

代码:

 1 //This is c program code!
 2 /* *=+=+=+=+* *** *=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
 3   * 文档信息: *** :~/WORKM/stutyCode/cCode/recipesProblemSolution/chapter06/test6_10.c
 4   * 版权声明: *** :(魎魍魅魑)MIT
 5   * 联络信箱: *** :guochaoxxl@163.com
 6   * 创建时间: *** :2020年11月21日的上午11:10
 7   * 文档用途: *** :数据结构与算法分析-c语言描述
 8   * 作者信息: *** :guochaoxxl(http://cnblogs.com/guochaoxxl)
 9   * 修订时间: *** :2020年第46周 11月21日 星期六 上午11:10 (第326天)
10   * 文件描述: *** :自行添加
11  * *+=+=+=+=* *** *+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+*/
12 #include <stdio.h>
13 
14 typedef struct _bio{
15     char name[15];
16     int rollNo;
17     int age;
18     float weight;
19 } Bio;
20     
21 void closeState(int clo, FILE *fPtr){
22     clo = fclose(fPtr);
23     if(clo == -1){
24     puts("File-closing failed.");
25     }
26     if(clo == 0){
27     puts("File is closed successfully.");
28     }
29     
30     return;
31 }       
32         
33 int main(int argc, char **argv)
34 {           
35     FILE *fPtr = fopen("agents.dat", "r");
36     if(fPtr != NULL){
37         printf("File agents.dat is opened successfully.
");
38         Bio bio;
39         int m = fscanf(fPtr, "%s %d %d %f", bio.name, &bio.rollNo, &bio.age, &bio.weight   );      
40     
41         while(m != EOF && m != -1){
42             printf("Name: %s, RoolNo: %d, Age: %d, Weight: %.1f
", bio.name, bio.rollNo   , bio.age, bio.weight);
43             m = fscanf(fPtr, "%s %d %d %f", bio.name, &bio.rollNo, &bio.age, &bio.weight   );  
44         }                                                                               
45         int clo;
46         closeState(clo, fPtr);
47     }else{
48         puts("File-open failed!");
49     }
50 
51     return 0;
52 }
原文地址:https://www.cnblogs.com/guochaoxxl/p/14054172.html