/* $Id: hiscore.c,v 1.1 1996/05/04 19:08:18 yoneyama Exp yoneyama $ */ /************************************************************************ * SameGame for X Window (sxsame) * * Copyleft (c) 1994-1996 Software Research Academy * ************************************************************************/ #include #include #include #include #include #include "config.h" #include "hiscore.h" static struct Hiscore hiscore[4]; static char *lockfn = LOCK_FILE; static char *hiscoref = HISCORE_FILE; extern char *same_dir; static int lock_file( #if NeedFunctionPrototypes int #endif ); int EntryHiscore(myscore, mode, ent) int myscore; int mode; int ent; { FILE *fp; int i, j; char *myname; char tmpf[MAXPATHLEN]; int new = 0; myname = (char *)getenv("LOGNAME"); if (MAXPATHLEN <= snprintf(tmpf, MAXPATHLEN ,"%s/%s", same_dir, hiscoref) ) { fprintf(stderr,"Error: hiscore file name too long.\n"); return -1; } umask(002); fp = fopen(tmpf,"rb"); if(fp != NULL) { fread(hiscore,sizeof(hiscore),1,fp); fclose(fp); } else { new = 1; /* Create new hiscore file */ for(j=0;j<4;j++) { for(i=0;i<10;i++) { hiscore[j].entry[i].score = 0; memset(hiscore[j].entry[i].name, 0, 20); strcpy(hiscore[j].entry[i].name, "--------"); } } } if(ent) { for(i=0;i<10;i++) { if(myscore > hiscore[mode].entry[i].score) { for(j=9;j>i;j--) { hiscore[mode].entry[j].score = hiscore[mode].entry[j-1].score; memcpy(hiscore[mode].entry[j].name, hiscore[mode].entry[j-1].name, 20); } hiscore[mode].entry[i].score = myscore; strncpy(hiscore[mode].entry[i].name, myname,20); break; } } if(i < 10 || new == 1) { if(lock_file(0) != 0) return(-1); umask(002); fp = fopen(tmpf, "wb"); fwrite(hiscore, sizeof(hiscore), 1, fp); fclose(fp); if(lock_file(1) != 0) return(-1); } return(i); } return(10); } static int lock_file(cmd) int cmd; { FILE *fp; char lkf[MAXPATHLEN]; int i; if (MAXPATHLEN <= snprintf(lkf, MAXPATHLEN, "%s/%s", same_dir, lockfn)) { fprintf(stderr,"Error: lock file name too long.\n"); return -1; } if(cmd == 1) { if(remove(lkf) != 0) { fprintf(stderr,"Error: can't unlock hiscore file.\n"); return(-1); } return(0); } umask(0777); re_lock: for(i=0;i= LOCK_RETRY) { if(remove(lkf) == 0) { fprintf(stderr,"Warning: remove the lock file and retry...\n"); goto re_lock; } fprintf(stderr,"Error: can't create lock file '%s'.\n", lkf); return(-1); } fclose(fp); return(0); } int GetHiscore(hi, mode) struct Hiscore *hi; { FILE *fp; char tmpf[MAXPATHLEN]; if (MAXPATHLEN <= snprintf(tmpf, MAXPATHLEN, "%s/%s", same_dir, hiscoref)) { fprintf(stderr,"Error: hiscore file name too long.\n"); return -1; } fp = fopen(tmpf,"rb"); if(fp == NULL) return(-1); fread(hiscore,sizeof(hiscore),1,fp); fclose(fp); memcpy(hi, &hiscore[mode], sizeof(struct Hiscore)); return(0); }