#include <stdio.h>
#include <stdlib.h>
#define N 3
typedef struct student stud;
typedef struct student{
int num;
char name[10];
int score[N];
//double aver;
stud *next;
}stud;
stud *Createlist();
void Outlink(stud *head,char *filename);
void Read(char *filename,stud *head);
int main(){
stud *head;
char filename[20];
printf("请输入待存入的文件名:\n");
gets(filename);
head=Createlist();
Outlink(head,filename);
Read(filename,head);
system("pause");
return 0;
}
/*创建链表数据*/
stud *Createlist(){
stud *head=NULL,*tail=NULL,*p;
printf("请输入学生信息:\n");
int i,x;
scanf("%d",&x);
while(x){
p=(stud *)malloc(sizeof(stud));
p->num =x;
scanf("%s",p->name );
for(i=0;i<N;i++){
scanf("%d",&p->score[i]);
}
p->next=NULL;
if(head==NULL){
head=p;
}else{
tail->next =p;
}
tail=p;
scanf("%d",&x);
}
return head;
}
/*将链表数据写入文件*/
void Outlink(stud *head,char *filename){
stud *p=head->next ;
FILE *fp1=fopen(filename,"w");
if(fp1==NULL){
printf("打开文件失败1\n");
return ;
}
while(p!=NULL){
fwrite(p,sizeof(stud),1,fp1);
p=p->next ;
}
printf("\n");
fclose(fp1);
}
/*从文件中读取数据并显示到屏幕上*/
void Read(char *filename,stud *head){
stud *p;
p=head;
FILE *fp=fopen(filename,"r");
if(fp==NULL){
printf("打开文件失败2\n");
return ;
}
printf("输出学生信息:\n");
int i;
while (p!=NULL){
fread(p,sizeof(stud),1,fp);
printf("%d\t%s\t",p->num ,p->name);
for(i=0;i<N;i++){
printf("%d\t",p->score[i]);
}
printf("\n");
p=p->next;
}
p->next=NULL;
}
链表,结构体,文件混合操作
最新推荐文章于 2023-04-16 21:49:01 发布