c语言基于链表的文件存储与读取

今天写了一下如何将链表中的数据存储到文件中

head为链表的起始结点

写入文件

void filewirte(LinkList head)
{
LinkList fd;
FILE *p=fopen("student_grad.txt", "w");
if(p==NULL)
{
printf("没有东西");
getchar();
exit(1);
}
fd=head->next;
while(fd)
{
fprintf(p,"%s %s %s %.0lf %.0lf %.0lf\n",fd->number,fd->name,fd->xingbie,fd->yuwen,fd->yingyu,fd->ave);
fd=fd->next;
}
fflush(stdin);
fclose(p);
}

读取文件

void fileread(LinkList head)
{

FILE *p=fopen("student_grad.txt", "r");
if(p==NULL)
{
fclose(p);
fflush(stdin);
filewirte(head);
}
else
{
int end1=0;
LinkList fd1,fd;//fd存数据到fd1
fd1=head;
fd=(LinkList)malloc(sizeof(Node));
fd->next=NULL;
while(1)
{
fd=(LinkList)malloc(sizeof(Node));
fd->next=NULL;
end1=fscanf(p,"%s %s %s %lf %lf %lf",fd->number,fd->name,fd->xingbie,&fd->yuwen,&fd->yingyu,&fd->ave);
if(end1==EOF)
{
break;
}
fd1->next=fd;
fd1=fd1->next;
fd1->next=NULL;
}
}
fflush(stdin);
fclose(p);
}

posted @ 2023-06-05 13:26  通信小九  阅读(111)  评论(0编辑  收藏  举报