📄 sort.c
字号:
#ifndef SORTBYVOTE
#define SORTBYVOTE
#include "stdio.h"
#include "shead.h"
#include "string.h"
void SortByVote()
{
candidate *s,*t;
int total=CANDIDATENUM;
candidate temp;
int recNumber=0;
int i,j,k;
char DataFile[10]="houshuan";
FILE * fp=fopen(DataFile,"rb");
clrscr();
if(fp==NULL)
{
printf("Open file %s fail!",DataFile);
perror("Open file fail");
getch();
return;
}
s=(candidate*)malloc(sizeof(candidate)*total);
if(s==NULL)
{
printf("allot memory fail!\n");
printf("press any key to continu...\n");
getch();
return;
}
while(fread(&temp,sizeof(candidate),1,fp)!=(int)NULL)
{
s[recNumber].Number=temp.Number;
strcpy(s[recNumber].Name,temp.Name);
strcpy(s[recNumber].intro,temp.intro);
s[recNumber].votenum=temp.votenum;
recNumber++;
if(recNumber>=total)
{
total+=INCREASE;
t=realloc(s,total*sizeof(candidate));
if(t==NULL)
{
printf("allot memory fail!\n");
printf("press any key to continu..\n");
free(s);/*释放内存*/
getch();
return;
}
s=t;
t=NULL;
}
}
fclose(fp);
fp=NULL;
/* 排序 */
for (i=0;i<recNumber-1;i++)
{
k=i;
for(j=i+1;j<recNumber;j++)
{
if(s[k].votenum<s[j].votenum) k=j;
}
if(k!=i)
{
temp.Number=s[i].Number;
strcpy(temp.Name,s[i].Name);
strcpy(temp.intro,s[i].intro);
temp.votenum=s[i].votenum;
s[i].Number=s[k].Number;
strcpy(s[i].Name,s[k].Name);
strcpy(s[i].intro,s[k].intro);
s[i].votenum=s[k].votenum;
s[k].Number=temp.Number;
strcpy(s[k].Name,temp.Name);
strcpy(s[k].intro,temp.intro);
s[k].votenum=temp.votenum;
}
}
fp=fopen(DataFile,"wb+");
for(i=0;i<recNumber;i++)
{
if(fwrite(&s[i],sizeof(candidate),1,fp)!=1)
{
printf("\nWrite file %s fail!end with any key.\n",DataFile);
perror("Write file fail!");
free(s);/*释放内存*/
getch();
exit(1);
}
}
fclose(fp);
fp=fopen(DataFile,"rb");
if(fp==NULL)
{
printf("\nOpen file %s fail!",DataFile);
perror("Open file fail");
free(s);/*释放内存*/
exit(1);
}
printf("\nNumber\tName\tvote\n");
while(fread(&temp,sizeof(candidate),1,fp)!=(int)NULL)
{
printf("%ld\t%s\t%d\n",temp.Number,temp.Name,temp.votenum);
}
fclose(fp);
printf("Press any key to continu...");
free(s);/*释放内存*/
getch();
}
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -