读取二进制文件时出问题了
程序代码:
#include <stdio.h> #include <stdlib.h> #include <malloc.h> struct student { char name[10]; char num[12]; int age; struct student *next; }; int main(void) { struct student *creat(void); void myprint(const struct student *); void save(FILE *, const struct student *); struct student *read_bin(FILE *); FILE *fp; struct student *head_1, *head_2; head_1 = creat(); myprint(head_1); fp = fopen("file", "wb"); save(fp, head_1); fclose(fp); fp = fopen("file", "rb"); head_2 = read_bin(fp); myprint(head_2); fclose(fp); system("pause"); return 0; } //建立单向链表 struct student *creat(void) { struct student *head, *p1, *p2; int flag; head = NULL; do { p2 = (struct student *)malloc(sizeof(struct student)); printf("input student's name,number and age:\n"); scanf("%s%s%d", p2->name, p2->num, &p2->age); if (head == NULL) head = p2; else p1->next = p2; p1 = p2; printf("\ninput 1 to keep on or input 0 to end:"); scanf("%d", &flag); } while (flag); p1->next = NULL; return head; } //输出单向链表 void myprint(const struct student *head) { struct student *p = (struct student *)head; while (p) { printf("%-10s\t%12s\t%2d\n", p->name, p->num, p->age); p = p->next; } } //保存链表至二进制文件 void save(FILE *fp, const struct student *head) { struct student *p = (struct student *)head; while (p) { fwrite(p, sizeof(p->next) + sizeof(p->num) + sizeof(p->age), 1u, fp); p = p->next; } } //创建链表读取二进制文件中的信息 struct student *read_bin(FILE *fp) { struct student *head, *p1, *p2; head = NULL; while (!feof(fp)) { p2 = (struct student *)malloc(sizeof(struct student)); fread(p2, sizeof(p2->name) + sizeof(p2->num) + sizeof(p2->age), 1u, fp); if (head == NULL) head = p2; else p1->next = p2; p1 = p2; } p1->next = NULL; return head; }
运行过程:
我输入了两行信息,却读出四行...
[此贴子已经被作者于2019-1-12 20:07编辑过]