帮忙看看这个文件的程序,谢谢!
题目是:stud.c文件存在,里面有5个学生数据(未排序), 现在要求插入一个学生,经平均分score[3]高低排序后,有存到stud_sort.c文件中,写出来了,运行了stud.c文件时多了一个学生,但stud_sort.c文件好像没产生,不知道怎么的。#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
#define NULL 0
int count=0; //count记录有多少个学生;
struct student
{
int num;
char name[10];
float score[4];
struct student *next;
}stu;
struct student *px_(struct student *head, int n)
{
struct student *p1,*p2,*p3,*p4, *new_head;
int i,j;
float a[6];
new_head=(struct student *)malloc(sizeof(struct student));
for(i=0;i<n;i++)
{
p1=head;
a[i]=head->score[3];
while(p1->next!=NULL) // 将最高分存放在a[i]中;
{
p1=p1->next;
if(a[i]<p1->score[3])
{
a[i]=p1->score[3];
}
}
p1=p2=head;
while(a[i]!=p1->score[3]) //找到平均分与a[i]相同的结点;
{
if(p1->next==NULL)
{
break;
}
p2=p1;
p1=p1->next;
}
if(p1==head) //删除找到的结点;
{
head=head->next;
}
else
{
p2->next=p1->next;
}
if(i==0) //建立新链表;
{
new_head->num=p1->num;
strcmp(new_head->name, p1->name);
for(j=0;j<4;j++)
{
new_head->score[j]=p1->score[j];
}
p3=p4=new_head;
}
else
{
p3->num=p1->num;
strcmp(p3->name, p1->name);
for(j=0;j<4;j++)
{
p3->score[j]=p1->score[j];
}
p4=p3;
}
p3=(struct student *)malloc(sizeof(struct student));
p4->next=p3; //连接结点;
free(p1); //释放p1所指的结点;
}
p4->next=NULL; //结束新链表;
return(new_head);
}
void save(struct student *head) //储存内容
{
FILE *p;
struct student *p1;
p1=head;
if((p=fopen("stud_sort.c", "wb"))==NULL) //以输出方式打开stud_sort.c文件;
{
printf("对不起,不能打开该文件\n");
exit(0);
}
while(1) //将链表内容依次输入到stud_sort.c文件中;
{
if(fwrite(p1, sizeof(struct student), 1, p)!=1)
printf("文件录入错误\n");
if(p1->next==NULL)
{
break;
}
p1=p1->next;
}
fclose(p);
}
int main()
{
FILE *p;
struct student *head, *p1,*p2, *pnew=NULL; //pnew为插入的学生, head为新的链表;
int j;
head=&stu;
if((p=fopen("stud.c", "ab"))==NULL) //以追加的输出方式打开stud.c;
{
printf("can't open the file\n");
exit(0);
}
printf("请插入学生数据:\n");
pnew=(struct student *)malloc(sizeof(struct student)); //为插入的新节点申请空间并对其赋值;
scanf("%d%s", &pnew->num, pnew->name);
for(j=0;j<3;j++)
{
scanf("%f", &pnew->score[j]);
}
pnew->score[j]=(pnew->score[0]+pnew->score[1]+pnew->score[2]) / 3;
pnew->next=NULL;
fwrite(pnew,sizeof(struct student),1,p); //将pnew中的数据写入到p所指向的文件内,即stud.c;
fclose(p);
if((p=fopen("stud.c", "rb"))==NULL) //以输入方式打开文件stud.c;
{
printf("can't open the file\n");
exit(0);
}
head=(struct student *)malloc(sizeof(struct student)); //为表头申请内存;
p1=head;
while(1) //将stud.c文件中的内容链接到新链表head后
{
fread(p1, sizeof(struct student),1,p);
count++;
if(p1->next=NULL)
{
break;
}
p2=p1;
p1=(struct student *)malloc(sizeof(struct student));
p2=p1->next;
}
head=px_(head, count); //对刚建的head链表调用排序函数;
save(head); //将排好序的head链表储存到stud_sort.c;
return 0;
}