使用fwrite和fread的二进制形式来保存结构数据是最好的
- #include<stdio.h>
- #include<stdlib.h>
- #define MAXTITL 40
- #define MAXAUTL 40
- #define MAXBKS 10
- struct book{
- char title[MAXTITL];
- char author[MAXAUTL];
- float value;
- };
- int main(void)
- {
- FILE *fp;
- struct book library[MAXBKS];
- int size = sizeof(struct book);
- int count = 0;
- int filecount;
- int index;
- if((fp = fopen("book.bat","a+b")) == NULL){ //采用追加并二进制模式
- puts("Can't open book.bat");
- exit(-1);
- }
- rewind(fp);
- while(count<MAXBKS && fread(&library[count],size,1,fp) == 1){ //当读取失败或者超过读取数目时推出循环
- if(count == 0){ //第一次才打印
- puts("Current contents of book.bat");
- }
- printf("%s by %s :$%.2f\n",library[count].title,library[count].author,library[count].value);//输出到屏幕上
- count++;
- }
- filecount = count;//保存原有的记录数
- if(count == MAXBKS){ //超了就不在输入了
- puts("The book.bat file is full.");
- getchar();
- exit(-1);
- }
- puts("Please add new book titles:");
- while(count<MAXBKS && gets(library[count].title) != NULL && library[count].title[0] != '\0'){
- puts("Now enter the author:");
- gets(library[count].author);
- puts("Now enter the value:");
- scanf("%f",&library[count++].value);
- while(getchar() != '\n'){
- continue;
- }
- if(count<MAXBKS){
- puts("Enter the next title:");
- }
- }
- if(count>0){
- puts("Here is the list of your book");
- 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,fp);//将新的纪录追加进去,注意参数的取值
- }
- else{
- puts("No books");
- }
- fclose(fp);
- puts("Bye");
- getchar();
- return 0;
- }