使用fwrite和fread的二进制形式来保存结构数据是最好的

 

 
  1. #include<stdio.h> 
  2. #include<stdlib.h> 
  3. #define MAXTITL 40 
  4. #define MAXAUTL 40 
  5. #define MAXBKS 10 
  6.  
  7. struct book{ 
  8.     char title[MAXTITL]; 
  9.     char author[MAXAUTL]; 
  10.     float value; 
  11. }; 
  12. int main(void
  13.     FILE *fp; 
  14.     struct book library[MAXBKS]; 
  15.     int size = sizeof(struct book); 
  16.     int count = 0; 
  17.     int filecount; 
  18.     int index; 
  19.      
  20.     if((fp = fopen("book.bat","a+b")) == NULL){
    //采用追加并二进制模式  
  21.         puts("Can't open book.bat"); 
  22.         exit(-1); 
  23.     } 
  24.     rewind(fp); 
  25.     while(count<MAXBKS && fread(&library[count],size,1,fp) == 1){
    //当读取失败或者超过读取数目时推出循环  
  26.         if(count == 0){
    //第一次才打印  
  27.             puts("Current contents of book.bat"); 
  28.         } 
  29.         printf("%s by %s :$%.2f\n",library[count].title,library[count].author,library[count].value);//输出到屏幕上  
  30.         count++; 
  31.     } 
  32.     filecount = count;//保存原有的记录数  
  33.     if(count == MAXBKS){
    //超了就不在输入了  
  34.         puts("The book.bat file is full."); 
  35.         getchar(); 
  36.         exit(-1); 
  37.     } 
  38.     puts("Please add new book titles:"); 
  39.     while(count<MAXBKS && gets(library[count].title) != NULL && library[count].title[0] != '\0'){ 
  40.         puts("Now enter the author:"); 
  41.         gets(library[count].author); 
  42.         puts("Now enter the value:"); 
  43.         scanf("%f",&library[count++].value); 
  44.         while(getchar() != '\n'){ 
  45.             continue
  46.         } 
  47.         if(count<MAXBKS){ 
  48.             puts("Enter the next title:"); 
  49.         } 
  50.      
  51.     } 
  52.     if(count>0){ 
  53.         puts("Here is the list of your book"); 
  54.         for(index=0;index<count;index++){ 
  55.             printf("%s by %s :$%.2f\n",library[index].title,library[index].author,library[index].value); 
  56.         } 
  57.         fwrite(&library[filecount],size,count-filecount,fp);//将新的纪录追加进去,注意参数的取值  
  58.     } 
  59.     else
  60.         puts("No books"); 
  61.     } 
  62.     fclose(fp); 
  63.     puts("Bye"); 
  64.    
  65.     getchar(); 
  66.     return 0; 
  67. }