1. 程式人生 > 實用技巧 >資料檔案——之讀取文字檔案中的結構

資料檔案——之讀取文字檔案中的結構

程式碼:

 1 //This is c program code!
 2 /* *=+=+=+=+* *** *=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
 3   * 文件資訊: *** :~/WORKM/stutyCode/cCode/recipesProblemSolution/chapter06/test6_10.c
 4   * 版權宣告: *** :(魎魍魅魑)MIT
 5   * 聯絡信箱: *** :[email protected]
 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.\n"); 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\n", 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 }