从文件中读取内容到链表有问题,求大神指点
#include<stdio.h>#include<stdlib.h>
#include<string.h>
#define name_max 10
typedef struct reader
{
char name[name_max];
long number;
int sex;
int classnumber;
int state;
struct reader *next;
}REA;
int menu();
REA *Initlist(REA *head);
REA *Display();
void Delete(REA *head);
int main()
{
int choose;
int flag=1;
REA *head=NULL;
while(flag)
{
choose=menu();
switch(choose)
{
case 1:
head=Initlist(head);
system("pause");
system("cls");
break;
case 2:
Delete(head);
head=Display();
system("pause");
system("cls");
break;
case 3:
Delete(head);
flag=0;
break;
default:
printf("wrong\n");
system("pause");
system("cls");
}
}
return 0;
}
int menu()
{
int choose,ret;
printf("**********************************************************************\n");
printf("* library system *\n");
printf("* 1 to initlist *\n");
printf("* 2 to display *\n");
printf("* 3 to exit *\n");
printf("**********************************************************************\n");
do
{
printf("please choose:");
ret=scanf("%d",&choose);
if(!ret)
{
fflush(stdin);
}
}while(!ret);
return choose;
}
REA *Initlist(REA *head)
{
FILE *fp;
REA *p=head,*s=NULL;
char name[name_max];
long number;
int sex;
int classnumber;
int state;
printf("please input students' name:\n");
scanf("%10s",name);
printf("please input students' number:\n");
scanf("%10ld",&number);
printf("please input students' sex:\n");
scanf("%d",&sex);
printf("please input students' classnumber:\n");
scanf("%d",&classnumber);
printf("please input students' state:\n");
scanf("%d",&state);
s=(REA *)malloc(sizeof(REA));
if(s==NULL)
{
printf("failure to creat line!\n");
exit(1);
}
if(head==NULL)
{
head=s;
}
else
{
while(p->next!=NULL)
{
p=p->next;
}
p->next=s;
}
strcpy(s->name,name);
s->number=number;
s->sex=sex;
s->classnumber=classnumber;
s->state=state;
s->next=NULL;
if((fp=fopen("E:\\library.txt","a"))==NULL)
{
printf("failure to open file\n");
exit(0);
}
fwrite(s,sizeof(REA),1,fp);
fclose(fp);
return head;
}
REA *Display()
{
FILE *fp;
REA *head=NULL,*s=NULL,*p=NULL;
if((fp=fopen("E:\\library.txt","r"))==NULL)
{
printf("failure to open file\n");
exit(0);
}
while(!feof(fp))
{
s=(REA *)malloc(sizeof(REA));
if(s==NULL)
{
printf("failure to creat line!\n");
exit(1);
}
fread(s,sizeof(REA),1,fp);
printf("name:%10s\n",s->name);
printf("number:%10ld\n",s->number);
printf("sex:%d\n",s->sex);
printf("classnumber:%d\n",s->classnumber);
printf("state:%d\n",s->state);
if(head==NULL)
{
head=s;
p=s;
}
else
{
p->next=s;
p=s;
}
}
fclose(fp);
return head;
}
void Delete(REA *head)
{
REA *p=head,*s=NULL;
while(p!=NULL)
{
s=p;
p=p->next;
free(s);
}
}