搜题
问题   更新时间2023/4/3 12:59:00

3.建立一个链表,每个结点包括:学号、姓名、年龄。数据从键盘上输入, 输入的学号为0时结束输入。链表建立后,将该链表中数据输出到屏幕上并存放到文件student.dat中。

#include "stdio.h" #define LEN sizeof(struct student) struct student { long num; char name[8]; int age; struct student *next; }; struct student *creat(void) { struct student *p1,*p2,*head; int n=0; p1=p2=(struct student *)malloc(LEN); printf("请输入学号:"); scanf("%ld",&p1->num); head=NULL; while(p1->num!=0) { printf("请输入姓名:"); scanf("%s",p1->name); printf("请输入年龄:"); scanf("%d",&p1->age); n++; if(n==1) head=p1; else p2->next=p1; p2=p1; p1=(struct student *)malloc(LEN); printf("请输入学号:"); scanf("%ld",&p1->num); } free(p1); if(head) p2->next=NULL; return head; } void print(struct student *head) { struct student *p=head; while(p) { printf("\n姓名:%s,学号:%ld,年龄:%d",p->name,p->num,p->age); p=p->next; } } void save(struct student *head) { struct student *p=head; FILE *fp; fp=fopen("stud","wb"); for(;p;) { if(fwrite(p,sizeof(struct student),1,fp)!=1) printf("File write error\n"); p=p->next; } fclose(fp); } struct student *access(void) { struct student *p1,*p2,*head=NULL; FILE *fp; fp=fopen("stud","rb"); int n=0; p1=p2=(struct student *)malloc(LEN); while(1) { if(fread(p1,sizeof(struct student),1,fp)!=1) printf("File read error\n"); n++; if(n==1) head=p1; else p2->next=p1; p2=p1; if(p1->next==NULL) break; p1=(struct student *)malloc(LEN); } if(head) p2->next=NULL; return head; } void main(void) { struct student *head; printf("请输入各结点数据:\n"); head=creat(); if(head) { print(head); save(head); free(head); head=access(); print(head); } }
王老师:19139051760(拨打)