Code:
//high Scores
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
int compare(const void*, const void*);
typedef struct
{
char name[20];
int hs;
} HS;
void show_hs(void)
{
FILE *f;
int length,i;
HS highscore[4];
if((f = fopen("hs.bin","rb")) == NULL)
{
printf("There are no High Scores");
}
else
{
fopen("hs.bin", "rb");
fread(&length, sizeof(int),1,f);
fread(&highscore, sizeof(char),length+1,f);
fclose(f);
printf("Highscores: \n");
for(i=0;i<2;i++)
{
printf("%d: %s - %d",i+1,highscore[i].name,highscore[i].hs);
}
}
}
void add_hs(int score)
{
FILE *f;
int res, length;
char plyr_nm[20];
char c;
int sw_ok = 0;
HS highscore[4];
while(!sw_ok)
{
printf("Please enter you name. (Max 3 characters long.\n");
res = scanf("%s%c", &plyr_nm, &c);
if (res != 2 || c != '\n' || strlen(plyr_nm) != 3 )
{
printf("%d %d",res,strlen(plyr_nm));
printf("Illegal input!\n");
printf("Try again : \n");
}
else
{
sw_ok = 1;
}
}
if((f = fopen("hs.bin","rb")) == NULL)
{
strcpy(highscore[0].name, plyr_nm);
highscore[0].hs = score;
f = fopen("hs.bin", "wb");
length = 20;
fwrite(&length,sizeof(int),1,f);
fwrite(&highscore,sizeof(HS),length+1,f);
fclose(f);
}
else
{
fopen("hs.bin", "rb");
fread(&length, sizeof(int),1,f);
fread(&highscore, sizeof(char),length+1,f);
fclose(f);
strcpy(highscore[4].name, plyr_nm);
highscore[4].hs = score;
qsort(highscore,4,sizeof(HS),compare); //Sort the highscores
f = fopen("hs.bin", "wb");
length = 20;
fwrite(&length,sizeof(int),1,f);
fwrite(&highscore,sizeof(HS),lengte+1,f);
fclose(f);
}
}
int compare( const void* a, const void* b )
{
HS* score1 = (HS*) a;
HS* score2 = (HS*) b;
if( score1->hs < score2->hs ) return -1;
else if( score1->hs == score2->hs ) return 0;
else return 1;
}