//4. 有一个记录学生信息的文件,每一行记录一名学生的信息,格式入下
//学号\t 姓名\t 性别\t 分数 1\t 分数 2\t 分数 3\n.
//要求:(1) 读取文件的内容, 串成一个链表。
// (2) 按照总分递减排序将结果保存到原文件。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 28
#define max 1024
typedef struct student
{
int num;
char name[N];
char sex;
float score[3];
}stu,*pstu;
typedef struct LIST
{
stu s;
struct LIST *next;
}list,*plist;
void insert(plist *head,plist *tail,stu s)
{
plist p=(plist)calloc(1,sizeof(list));
int index=0;
p->s.num=s.num;
strcpy(p->s.name,s.name);
p->s.sex=s.sex;
p->s.score[0]=s.score[0];
p->s.score[1]=s.score[1];
p->s.score[2]=s.score[2];
p->next=NULL;
if( (*head)==NULL )
{
(*head)=p;
(*tail)=p;
}
else
{
(*tail)->next=p;
(*tail)=p;
}
}
void showList(plist head,plist tail)
{
plist p=head;
while( p!=NULL )
{
printf("%d\t%s\t%c\t%4.1f\t%4.1f\t%4.1f\n",p->s.num,p->s.name,p->s.sex,p->s.score[0],p->s.score[1],p->s.score[2]);
p=p->next;
}
}
|
void sort(plist *head,plist *tail)
{
plist tmp=(plist)calloc(1,sizeof(list));
plist pre=(*head),pcur=(*head);
if((*head)==NULL)
{
return;
}
while(pre!=NULL)
{
pcur=pre->next;
while(pcur!=NULL)
{
if( (pcur->s.score[0]+pcur->s.score[1]+pcur->s.score[2])>(pre->s.score[0]+pre->s.score[1]+pre->s.score[2]) )
{
memcpy(tmp,pre,sizeof(stu)); //不能拷贝整个链表节点,因为这样会把next的值也拷贝过去,链表的状态改变了;
memcpy(pre,pcur,sizeof(stu));
memcpy(pcur,tmp,sizeof(stu));
}
pcur=pcur->next;
}
pre=pre->next;
}
}
void writeFile(plist head,plist tail,FILE *fp)
{
fseek(fp,0,SEEK_SET);
while(head!=NULL)
{
fprintf(fp,"%d\t%s\t%c\t%4.1f\t%4.1f\t%4.1f\n",head->s.num,head->s.name,head->s.sex,head->s.score[0],head->s.score[1],head->s.score[2]);
head=head->next;
}
}
int main()
{
FILE *fp=fopen("student.txt","r+");
plist head=NULL;
plist tail=NULL;
stu s;
if(NULL==fp)
{
perror("fopen");
return -1;
}
fseek(fp,0,SEEK_SET);
while(fflush(stdin),memset(&s,0,sizeof(stu)),fscanf(fp,"%d %s %c %f %f %f",&s.num,&s.name,&s.sex,&s.score[0],&s.score[1],&s.score[2])!=EOF)
{
insert(&head,&tail,s);
}
showList(head,tail);
sort(&head,&tail);
printf("after sort\n");
showList(head,tail);
writeFile(head,tail,fp);
system("pause");
}
|