?? sort.c
字號(hào):
/* sscore.c:按玩家成績(jī)排序*/
#include "stdio.h"
void SortByScore()
{
int i,j,k;
player TmpS; /*定義進(jìn)行操作時(shí)的臨時(shí)結(jié)構(gòu)體變量*/
player s[SIZE];/*SIZE,在score.h頭文件中定義的常量,值為100 */
int recNumber = 0;
char DataFile[40] = "record"; /*DataFile存儲(chǔ)玩家成績(jī)信息的文件名*/
FILE *fp;/*====fp指針指向存儲(chǔ)數(shù)據(jù)的文件名====*/
/*以讀的方式打開(kāi)文件,如文件不存在,提示錯(cuò)誤*/
fp=fopen(DataFile,"rb");
if (fp == NULL)
{
printf("\nOpen file %s fail!End with any key\n",DataFile);
perror("Open file fail");
getch();
exit(1);
}
/*將文件中要排序的信息存入結(jié)構(gòu)體數(shù)組*/
while((fread(&TmpS,sizeof(player),1,fp)) != (int)NULL)
{
strcpy(s[recNumber].name, TmpS.name);
s[recNumber].score=TmpS.score;
recNumber++;
}
fclose(fp);
/*如果文件中有記錄,則將各條記錄按成績(jī)值排序*/
if(recNumber>1)
{
/*用選擇排序法進(jìn)行排序*/
for(i=0;i<recNumber-1;i++)
{
k = i;
for(j=i+1;j<recNumber;j++)
{
if(s[k].score>s[j].score) k = j;
}
strcpy(TmpS.name,s[k].name);
TmpS.score = s[k].score;
strcpy(s[k].name,s[i].name);
s[k].score = s[i].score;
strcpy(s[i].name,TmpS.name);
s[i].score = TmpS.score;
}
/*====將排序好的結(jié)構(gòu)體記錄寫入文件====*/
fp=fopen(DataFile,"wb+");
if (fp == NULL)
{
printf("\nSet up file %sfail !end with anykey.\n",DataFile);
perror("Set up fail");
getch();
exit(1);
}
for(i=0; i<recNumber; i++)
{
if(fwrite(&s[i],sizeof(player),1,fp)!=1)
{
printf("\nWrite file %s fail!end with anykey.\n",DataFile);
perror("Write file fail!");
getch();
exit(1);
}
}
fclose(fp);
}
/*====顯示排序后的文件====*/
printf("the player's score in file %s is as flow:.\n",DataFile);
fp=fopen(DataFile,"rb");
if (fp == NULL)
{
printf("\nOpen file%sfail!End with any key \n",DataFile);
perror("Open file fail");
getch();
exit(1);
}
printf("\nname\tscore\n");
while(fread(&TmpS,sizeof(player),1,fp) != (int)NULL)
{
printf("\n%s\t%d\n",TmpS.name,TmpS.score);
}
fclose(fp);
getch();
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -