K
da ich gerade nichts besseres zu tun habe, zeige ich dir mal wie man die macht der strukturen in kombination mit der macht von scanf nutzt:
#include <stdio.h>
#include <string.h>
#define HIGHSCORE_SIZE 10
#define HIGHSCORE_FILENAME "highscore.txt"
struct highscore_entry
{
int score;
char name[9];
};
struct highscore_entry highscore[HIGHSCORE_SIZE];
void
init_highscore (void)
{
int i;
for(i=0; i<HIGHSCORE_SIZE; ++i)
{
highscore[i].score=0;
strcpy(highscore[i].name,"---");
}
}
int
add_highscore (int score, char *name)
{
int i,j;
for(i=0; i<HIGHSCORE_SIZE; ++i)
if(score>=highscore[i].score)
break;
if(i==HIGHSCORE_SIZE) return 0; /* score wasnt added */
for(j=HIGHSCORE_SIZE-1; j<i; --j)
{
highscore[j].score=highscore[j-1].score;
strcpy(highscore[j].name,highscore[j-1].name);
}
highscore[i].score=score;
strcpy(highscore[i].name,name);
return 1; /* score was added to highscore table */
}
void
load_highscore (void)
{
FILE *fp;
int i;
init_highscore();
fp=fopen(HIGHSCORE_FILENAME,"r");
if(fp)
{
for(i=0; i<HIGHSCORE_SIZE; ++i)
fscanf(fp,"%d %8[^/n]/n",&highscore[i].score,highscore[i].name);
fclose(fp);
}
}
void
save_highscore (void)
{
FILE *fp;
int i;
fp=fopen(HIGHSCORE_FILENAME,"w");
if(fp)
{
for(i=0; i<HIGHSCORE_SIZE; ++i)
fprintf(fp,"%09d %[^/n]/n",highscore[i].score,highscore[i].name);
fclose(fp);
}
}
void
print_highscore (void)
{
int i;
for(i=0; i<HIGHSCORE_SIZE; ++i)
printf("%02d. %09d %s\n",i+1,highscore[i].score,highscore[i].name);
}
natürlich kannst du die highscore-tabelle auch einfach mit fwrite() binär speichern.