数据文件——之将结构写入文本文件

代码:

 1 //This is c program code!
 2 /* *=+=+=+=+* *** *=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
 3   * 文档信息: *** :~/WORKM/stutyCode/cCode/recipesProblemSolution/chapter06/test6_8.c
 4   * 版权声明: *** :(魎魍魅魑)MIT
 5   * 联络信箱: *** :guochaoxxl@163.com
 6   * 创建时间: *** :2020年11月21日的上午09:11
 7   * 文档用途: *** :数据结构与算法分析-c语言描述
 8   * 作者信息: *** :guochaoxxl(http://cnblogs.com/guochaoxxl)
 9   * 修订时间: *** :2020年第46周 11月21日 星期六 上午09:11 (第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 int main(int argc, char **argv)
22 {       
23     char flag = 'y';
24     FILE *fPtr = fopen("agents.dat", "w");
25     if(fPtr != NULL){
26         printf("File agents.dat is opened successfully.\n");
27         Bio bio;
28         while(flag == 'y'){
29             printf("Enter name, rooNo, age and weight of agent: ");
30             scanf("%s %d %d %f", bio.name, &bio.rollNo, &bio.age, &bio.weight);
31             fprintf(fPtr, "%s %d %d %.1f\n", bio.name, bio.rollNo, bio.age, bio.weight);
32             int tmp = getchar();
33             //fflush(stdin);
34             printf("Any more records(y/n): ");
35             scanf("%c", &flag);
36         }
37         int clo = fclose(fPtr);
38         if(clo == -1){
39             puts("File-closing failed!");
40         }
41         if(clo == 0){
42             puts("File is closed successfully.");
43         }
44     }else{
45         puts("File-open failed!");
46     }
47 
48     return 0;
49 }

 

posted @ 2020-11-28 21:21  叕叒双又  阅读(150)  评论(0编辑  收藏  举报