#include <stdio.h>#include<stdlib.h>#defineMaxtlen 70#defineMaxalen 70#defineMaxbks 10structbook{CharTitle[maxtlen]; CharAuthor[maxalen]; floatvalue;};intMain () {structBook Library[maxbks];//Library intCount =0, index, FileCount; intSize =sizeof(structbook);//This is worth noting .FILE *Pbooks; if(Pbooks = fopen ("Book.dat","a+b")) ==NULL) {fputs ("Can not open Book.dat file\n", stderr); Exit (1); } rewind (Pbooks); while(Count < Maxbks && Fread (&library[count],size,1, pbooks) = =1){ if(Count = =0) {puts ("Current contents of Book.dat:"); } printf ("%s by%s: $%.2f\n", Library[count].title,library[count].author,library[count].value); Count++; } filecount=count; if(Count = =maxbks) {fputs ("The book.dat file is full", stderr); Exit (2); } puts ("Add the new book, title:"); while(Count < Maxbks && gets (library[count].title)! = NULL && library[count].title[0] !=' /') {puts ("The Author:"); Gets (Library[count].author); Puts ("The value:"); scanf ("%f", &library[count++].value); while(GetChar ()! ='\ n'){ Continue; } if(Count <maxbks) {Puts ("---Continue---"); } } if(Count >0) {puts ("Here is the list of your books:"); for(index =0; index<count; index++) {printf ("%s by%s: $%.2f\n", Library[index].title,library[index].author,library[index].value); } fwrite (&library[filecount],size,count-filecount,pbooks); }Else{puts ("No books? Too bad\n"); } puts ("bye\n"); Fclose (Pbooks); return 0;}
Current contents of Book.dat:c language authoritative guide by Jimmy: $ 68.00 PHP Project Daquan by Jimmy: $ 99.90 New book, title:
C language: Storing the structure in a file