第 14 章 结构和其他数据形式(把结构内容保存到文件中)
程序员文章站
2022-07-07 20:58:32
1 /* 2 booksave.c -- 在文件中保存结构中的内容 3 */ 4 5 #include 6 #include 7 #include 8 9 #define MAXTITL 40 10 #define MAXAUTL 40 ......
1 /*----------------------------------------- 2 booksave.c -- 在文件中保存结构中的内容 3 -----------------------------------------*/ 4 5 #include <stdio.h> 6 #include <stdlib.h> 7 #include <string.h> 8 9 #define MAXTITL 40 10 #define MAXAUTL 40 11 #define MAXBKS 10 //最大书籍数量 12 13 char* s_gets(char *st, int n); 14 15 struct book 16 { 17 char title[MAXTITL]; 18 char author[MAXAUTL]; 19 float value; 20 }; 21 22 int main() 23 { 24 struct book library[MAXBKS]; 25 int index, filecount; 26 FILE *pbooks; 27 28 if ((pbooks = fopen("book.dat", "a+b")) == NULL) 29 { 30 fputs("Can't open book.dat file\n", stderr); 31 exit(EXIT_FAILURE); 32 } 33 34 rewind(pbooks); //定位到文件开始 35 36 int count = 0, size = sizeof(struct book); 37 38 while (count != MAXBKS && fread(&library[count], size, 1, pbooks) == 1) 39 { 40 if (count == 0) 41 puts("Current contents of book.dat:"); 42 43 printf("%s by %s: $%.2f\n" 44 , library[count].title, library[count].author, library[count].value); 45 46 ++count; 47 } 48 49 filecount = count; 50 51 if (count == MAXBKS) 52 { 53 fputs("The book.dat file is full.", stderr); 54 exit(2); 55 } 56 57 puts("Please add new book titles."); 58 puts("Press [enter] at the start of a line to stop."); 59 60 while (count != MAXBKS && s_gets(library[count].title, MAXTITL) != NULL 61 && library[count].title[0] != '\0') 62 { 63 puts("Now enter the author."); 64 65 s_gets(library[count].author, MAXAUTL); 66 67 puts("Now enter the value."); 68 69 scanf("%f", &library[count++].value); 70 71 while (fgetc(stdin) != '\n') continue; //清理输入行 72 73 if (count != MAXBKS) 74 puts("Enter the next title."); 75 } 76 77 if (count > 0) 78 { 79 puts("Here is the list of your books:"); 80 81 for (index = 0; index != count; ++index) 82 printf("%s by %s: $%.2f\n" 83 , library[index].title, library[index].author, library[index].value); 84 85 fwrite(&library[filecount], size, count - filecount, pbooks); 86 } 87 else 88 puts("No books? Too bad.\n"); 89 90 puts("Bye.\n"); 91 fclose(pbooks); 92 93 return 0; 94 } 95 96 char* s_gets(char *st, int n) 97 { 98 char *ret_val, *find; 99 100 if (ret_val = fgets(st, n, stdin)) 101 { 102 if (find = strchr(st, '\n')) 103 *find = '\0'; 104 else 105 while (fgetc(stdin) != '\n') continue; 106 } 107 108 return ret_val; 109 }
上一篇: 这就是人生,这就是生活