二次运行文件不正常。。。
第一次运行建立文件,追加了几个记录,
第二次运行文件的时候,回显不正常,第一个记录没有书名和作者,
而且后面每个.value的值都是第一个.value的值,错误出在哪里了呢?
//booksave.c 把结构内容保存到文件中 #include <stdio.h>#include <stdlib.h> //为malloc()函数提供原型#define BOOKS 10 //最多容纳多少本书#define NAMES 40 //书名#define ZUOZHE 40 //作者名struct book{ char title[NAMES]; char author[ZUOZHE]; float value;};int main(int argc,char *argv[]){ struct book library[BOOKS]; FILE *fp; int count = 0; int filecount,index; int size = sizeof(struct book); if(argc != 2) { fputs("command error\n",stderr); exit(1); } if((fp = fopen(argv[1],"a+b")) == NULL) { fprintf(stderr,"Can't open %s\n",argv[1]); exit(2); } rewind(fp); while(count < BOOKS && fread(&library[count],size,1,fp) == 1) { if(count = 0) fprintf(stdout,"Current contents of %s:\n",argv[1]); fprintf(stdout,"%s by %s: $%.2f\n",library[count].title,library[count].author,library[count++].value); } filecount = count; if(count == BOOKS) { fprintf(stderr,"The %s file is full",argv[1]); exit(3); } fputs("Please add new book titles.\n",stdout); puts("Press [enter] at the start of a line to stop."); while(count < BOOKS && 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 < BOOKS) puts("Enter the next title"); } if(count > 0) { puts("Here is the list of your books: "); for(index = 0;index < count; index++) fprintf(stdout,"%s by %s: $%.2f\n",library[index].title,library[index].author,library[index].value); fwrite(&library[filecount],size,count - filecount,fp); } else fputs("No books? Too bad.\n",stderr); puts("Bye.\n"); fclose(fp); return 0;}