
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 ", 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 " 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] != '