这是我写的代码。如果按下面的有效代码的话只能读出链表的head值。如果按注释掉的来编译话,就直接出错了。还有其他方法实现吗!?
# include "stdio.h"
# include "stdlib.h"
# include "string.h"
# include "malloc.h"
struct student
{
char name[10];
char id[20];
float score;
struct student * next;
};
struct student * creat()//创建一个链表
{
struct student * head;
struct student * back;
struct student * front;
head=NULL;
back=front=(struct student *)malloc(sizeof(struct student));
printf("请输入学生姓名,学号和成绩:\n");
scanf("%s %s %f",front->name,front->id,&front->score);
int n=1;
while(strcmp(front->name,"#")!=0)
{
n++;
if(head==NULL)
head=front;
else
{
back->next=front;
back=front;
front=(struct student *)malloc(sizeof(struct student));
scanf("%s %s %f",front->name,front->id,&front->score);
}
}
back->next=NULL;
FILE * fp;
fp=fopen("student_list","a+");
if((fp=fopen("student_list","a+"))==NULL)
{
printf("File open error!");
return NULL;
exit(0);
}
else
{
fwrite(head,sizeof(struct student),n,fp);
fclose(fp);
return head;
}
}
void print(struct student * head)//打印输出链表
{
struct student *p;
p=head;
if(p==NULL)
{
printf("The list is empty..!Please check.....!\n");
exit(0);
}
while(p!=NULL)
{
printf("%10s%20s%5.1f\n",p->name,p->id,p->score);
p=p->next;
}
}
void main()
{
struct student * head;
FILE *f;
/*f=fopen("student_list","a+");
if((f=fopen("student_list","a+"))!=NULL)
for(int k=0;kname,head->id,head->score);
}
else
{
head=creat();
for(int k=0;kname,head->id,head->score);
}
}*/
head=creat();
f=fopen("student_list","a+");
fread(head,sizeof(struct student),1,f);
printf("%10s%20s%5.1f\n",head->name,head->id,head->score);
}
|