|
需要写入一组学生数据,包括学号,姓名,三门课程的成绩以及均分,出错的地方如下:
while(fwd!=NULL)
{
if (fwrite(&fwd,LEN,1,fp)!=1)//依次写入每行的信息
printf("Finish writing\n");
fwd=fwd->next;
}
还有用注释隔离出来的子函数是想读入文件的数据然后输出,看看有没有错,不知道写的对不对。。。
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define NULL 0
#define LEN sizeof(struct stu_data)
#define F_NAMELEN 10
#define STU_NAMELEN 10
#define STU_MAX 5
#define CRS_MAX 3
struct stu_data
{
long num;
char name[STU_NAMELEN];
float course[CRS_MAX];
float aver;
struct stu_data *next;
};
FILE *fp;
struct stu_data *Crt(void)//创建链表并写入学生数据
{
int course;
struct stu_data *head,*fwd,*bk;
head=bk=(struct stu_data*)malloc(LEN);//第一个结点不存储信息
fwd=head->next=(struct stu_data*)malloc(LEN);//开辟第二个结点
printf("Max student %d Max course %d\n",STU_MAX,CRS_MAX);
printf("Now input the infomations please\n");
printf("Input 0 as number to cease\n");//输出三行提示信息
while(1)
{
printf("Num => ");
scanf("%ld",&fwd->num);//输入学号
if(!fwd->num)
break;
printf("Name => ");
scanf("%s",&fwd->name);//输入姓名
for (fwd->aver=0,course=0;course<CRS_MAX;course++)
{
printf("Subject %d => ",course+1);
scanf("%f",&fwd->course[course]);//输入各个课程的成绩
fwd->aver+=fwd->course[course];
}
fwd->aver/=CRS_MAX;//计算均分
bk=fwd;
fwd=fwd->next=(struct stu_data*)malloc(LEN);//开辟下一个空间
}
bk->next=NULL;
return head;
}
void save_file(struct stu_data *fwd)//将链表存入新建的文件中
{
if ((fp=fopen("stu_data.txt","wb"))==NULL)
{
printf("File open failed\n");
exit(0);
/* return; */
}
while(fwd!=NULL)
{
if (fwrite(&fwd,LEN,1,fp)!=1)//依次写入每行的信息
printf("Finish writing\n");
fwd=fwd->next;
}
}
/*void print(struct stu_data *fwd)//打开文件,输出存入的信息
{
rewind(fp);
printf("Now look into the document contents\n");
while((fwd=fwd->next)!=NULL)
{
fwrite(fwd,LEN,1,fp);
printf("\n");
}
fclose(fp);
}*/
void main()
{
struct stu_data *head;
head=Crt();
save_file(head);
// print(head);
}
|
|