69,373
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
typedef struct StuNode
{
int num;
char name[20];
char sex[4];
int english_score;
int c_score;
struct StuNode *next;
}StuList;
void main()
{
StuList *input();
void read_file();
void write_file(StuList *head);
StuList *head;
head=input();
write_file(head);
read_file();
system("pause");
}
StuList *input()
{
int x;
bool z=true;
StuList *head,*stu;
head = NULL;
while(z)
{
stu = (StuList*)malloc(sizeof(StuList));
scanf("%d%s%s%d%d",&stu->num,&stu->name,&stu->sex,&stu->english_score,&stu->c_score);
stu->next = head;
head=stu;
printf("是否继续输入下一项记录(1、继续 2、退出):");
scanf("%d",&x);
if(x == 1)
{
z=true;
}
else if( x == 2)
{
z=false;
}
}
return head;
}
void write_file(StuList *head)
{
FILE *fp;
if((fp=fopen("student.txt","a")) == NULL)
{
printf("加载失败!");
return;
}
for (head ; head != NULL ; head = head->next)
{
fwrite(head,sizeof(StuList),1,fp);
}
fclose(fp);
}
void read_file()
{
StuList *head,*stu,*r,*t; //改动:添加*t,作为标记
FILE *fp;
if((fp=fopen("student.txt","r"))==NULL)
{
printf("加载失败!");
}
head=r=(StuList*)malloc(sizeof(StuList));
while(!feof(fp))
{
stu=(StuList*)malloc(sizeof(StuList));;
fread(stu,sizeof(StuList),1,fp);
r->next=stu;
t=r;
r=stu;
}
t->next=NULL;//改动,添加*t
fclose(fp);
if(head == NULL)
{
printf("没有数据!");
}
else
{
for( head ;head != NULL;head = head -> next )
printf("学号:%5d 姓名:%5s 性别:%5s 英语成绩:%5d C语言成绩:%d\n",
head->num,head->name,head->sex,head->english_score,head->c_score);
}
}