怎么把文件里的数据读到结构体里呢?
怎么把文件里的数据读到结构体里呢?如果用fread该怎么办
BOOK *store(BOOK *head) //存储 { FILE *fp; BOOK *ptr, *p; p = head; if((fp = fopen("bookinfo.txt","w")) == NULL){ printf("File open error!\n"); exit(0); } for(ptr = head;ptr;ptr = ptr->next) fprintf(fp,"%d %s %s %6.2f\n",ptr->num,ptr->writer,ptr->name,ptr->price); if(fclose(fp)){ printf("Can not close the file!\n"); exit(0); } return head; }
BOOK *store(BOOK *head) //存储 { FILE *fp; BOOK *ptr, *p; p = head; if((fp = fopen("bookinfo.txt","w")) == NULL){ printf("File open error!\n"); exit(0); } for(ptr = head;ptr;ptr = ptr->next) fprintf(fp,"%d %s %s %6.2f\n",ptr->num,ptr->writer,ptr->name,ptr->price); if(fclose(fp)){ printf("Can not close the file!\n"); exit(0); } return head; }
BOOK *read() { BOOK *ptr, *head, *tail; head = tail = NULL; int num; char writer[CHAR], name[CHAR]; double price; if((fp = fopen("bookinfo.txt","r")) == NULL){ printf("open fail!\n"); exit(0); } while(! feof(fp)) { ptr=(BOOK *)malloc(size); if(head == NULL) head = ptr; else tail->next = ptr; tail = ptr; fscanf(fp,"%d %s %s %lf",&num, writer, name, &price); ptr->num = num; strcpy(ptr->writer, writer); strcpy(ptr->name, name); ptr->price = price; } tail = NULL; return head; }