文件问题有点生疏,同学向你诚恳请教
想文件stud.c输出5个学生的数据,然后又输出来,我用数组已经做出来了,但想到一些排序,插入等操作,就换成链表来做,结果over了,不要给我代码,就具体说说,那个地方出了问题,或是概念有什么误差,谢谢!!#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define NULL 0
struct student
{
int num;
char name[10];
float score[4];
struct student *next;
}stu;
struct student *creat(struct student *head, int n) //建立链表
{
struct student *p1, *p2;
int i, j;
p2=p1=(struct student *)malloc(sizeof(struct student));
printf("请输入数据:\n");
for(i=0;i<n;i++)
{
scanf("%d%s%", &p1->num, p1->name);
for(j=0;j<3;j++)
{
scanf("%f", &p1->score[j]);
}
p1->score[j]=(p1->score[0]+p1->score[1]+p1->score[2]) / 3;
if(i==0)
{
head=p1;
}
p2=p1;
p1=(struct student *)malloc(sizeof(struct student));
p2->next=p1;
}
free(p1);
p2->next=NULL;
return(head);
}
void save(struct student *head) //存放数据到stud.c文件中
{
FILE *p;
struct student *p1;
p1=head;
if((p=fopen("stud.c", "wb"))==NULL)
{
printf("对不起,不能打开该文件\n");
exit(0);
}
while(1)
{
if(fwrite(p1, sizeof(struct student), 1, p)!=1)
printf("文件录入错误\n");
if(p1->next=NULL)
{
break;
}
p1=p1->next;
}
}
int main()
{
FILE *p1;
int j;
struct student *head, *p=NULL;
head=&stu;
head=creat(head, 5);
save(head);
p=head;
p1=fopen("stud.c", "rb");
printf("请输出数据 :\n");
printf("学号\t姓名\t学科1\t学科2\t学科3\t平均分\n");
while(1) //读入stud.c中的数据,并输出。
{
fread(p, sizeof(struct student), 1, p1);
printf("%d\t%s\t", p->num, p->name);
for(j=0;j<4;j++)
{
printf(" %.2f\t", p->score[j]);
}
if(p->next==NULL)
{
break;
}
p=p->next;
}
fclose(p1);
return 0;
}