#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define
LEN
sizeof( struct student )
#define
STU_SUM
4 //定义学生的总人数
#define
CLASS_SUM
2 //定义班级的总数
typedef struct student
{
int number;//学号
char name[10];//姓名
int clas;//班级
int mark;//成绩
int ranking;//排名
struct student *next;
}*Stu;
typedef struct
Class
{
int clas;
int mark;
struct Class *next;
}*Cla;
void Init( Cla &c );//初始化班级
void Creat_File();//创建文件
void Read_File( Stu &s );//读取文件
void Creat_List( Stu &s );//建立链表
void Total( Cla &c, Stu s );//计算班级总分
void Arrang( Cla &c );//班级成绩排序高到低
void Save( Cla c );//保存信息
int main()
{
Cla C;
Stu S;
Creat_List(S);
Init( C );
Creat_File();
Read_File(S);
Total( C, S );
Arrang( C );
Save( C );
return 0;
}
//初始化班级
void Init( Cla &c )
{
c = (Cla) malloc (sizeof(struct Class));
if( !c )
exit(0);
c->next = NULL;
Cla temp;
int i;
for( i=1; i<=CLASS_SUM; i++ )
{
temp = (Cla) malloc (sizeof(struct Class));
temp->clas = i;
temp->mark = 0;
temp->next = c->next;
c->next = temp;
}
}
//创建文件
void Creat_File()
{
FILE *fp;
Stu temp;
temp = (Stu) malloc (LEN);
int i;
if( !(fp=fopen("d:\\f1.txt","w")) )
exit(0);
for( i=0; i<STU_SUM; i++ )
{
printf("输入第 %d 个学生的信息\n", i+1);
printf("输入学号:"); scanf("%d", &temp->number);
printf("输入姓名:"); scanf("%s", temp->name);
printf("输入班级:"); scanf("%d", &temp->clas);
printf("输入成绩:"); scanf("%d", &temp->mark);
printf("输入排名:"); scanf("%d", &temp->ranking);
fprintf(fp, "%d %s %d %d %d %d\n", temp->number,temp->name,temp->clas,temp->mark,temp->ranking);
}
fclose(fp);
}
//读取文件
void Read_File( Stu &s )
{
if( !s )
return;
FILE *fp;
Stu
temp;
char c;
if(!(fp = fopen("d:\\f1.txt","r")))
return;
while( !feof(fp) )
{
temp = (Stu) malloc (LEN);
fscanf(fp, "%d %s %d %d %d %d%c", &temp->number,temp->name,&temp->clas,&temp->mark,&temp->ranking,&c);
temp->next = s->next;
s->next = temp;
}
fclose(fp);
}
//建立链表
void Creat_List( Stu &s )
{
s = (Stu) malloc (LEN);
if( !s )
exit(0);
s->next = NULL;
}
//计算班级总分
void Total( Cla &c, Stu s )
{
if( !c || !s )
return;
Stu p = s->next;
Cla f = c->next;
while( p )
{
f = c->next;
while( f )
{
if( f->clas==p->clas )
f->mark += p->mark;
f = f->next;
}
p = p->next;
}
}
//班级成绩排序
void Arrang( Cla &c )
{
Cla d, p = c->next, fd = c, temp = c->next;
if( !p || !p->next )
return;
while( temp )
{
d = p = temp;
fd = c->next;
while( p )
{
if(
p->mark < d->mark )
{
d = p;
while( fd->next != d )
fd = fd->next;
}
p = p->next;
}
if( d == temp )
temp = temp->next;
fd->next = d->next;
d->next = c->next;
c->next = d;
}
}
//保存信息
void Save( Cla c )
{
Cla temp = c->next;
if( !temp )
return;
FILE *fp;
if( !(fp = fopen("d:\\f2.txt","w")))
exit(0);
while( temp )
{
fprintf(fp, "%d %d\n", temp->clas,temp->mark);
temp = temp->next;
}
fclose(fp);
}