From 191f818c933d22d69cf94fe32e24f1a4c6fa460b Mon Sep 17 00:00:00 2001 From: twistdroach Date: Fri, 3 Feb 2023 00:27:32 -0500 Subject: [PATCH] Write scores to a tmp file first, then rename it over the original score file. --- common.h | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/common.h b/common.h index 5458639..b2d38a9 100644 --- a/common.h +++ b/common.h @@ -20,6 +20,7 @@ You should have received a copy of the CC0 Public Domain Dedication along with t #include "config.h" #define FOPEN_FAIL -10 #define ENV_VAR_OR_USERNAME (getenv("NB_PLAYER")?getenv("NB_PLAYER"):getenv("USER")) +#define MAXPATHSIZE 1000 FILE* score_file; byte score_write(const char* path, long wscore, byte save_to_num){// only saves the top 10, returns the place in the chart score_file=fopen(path,"r"); @@ -36,6 +37,9 @@ byte score_write(const char* path, long wscore, byte save_to_num){// only saves #endif char name_buff[save_to_num_][60]; long score_buff[save_to_num_]; + char tmp_path[MAXPATHSIZE + 8] = {0}; + strcpy(tmp_path, path); + strcat(tmp_path, ".XXXXXX"); memset(name_buff,0,save_to_num_*60*sizeof(char) ); memset(score_buff,0,save_to_num_*sizeof(long) ); @@ -52,8 +56,8 @@ byte score_write(const char* path, long wscore, byte save_to_num){// only saves memset(scanned_name,0,60); scanned_score=0; } - score_file = fopen(path,"w+") ;//will get rid of the previous text - if(!score_file){ + FILE* tmp_score_file = fdopen(mkstemp(tmp_path), "w"); + if(!tmp_score_file){ return FOPEN_FAIL; } byte scores_count=location;//if 5 scores were scanned, it is 5. the number of scores it reached @@ -62,32 +66,41 @@ byte score_write(const char* path, long wscore, byte save_to_num){// only saves for(byte i=0;i<=scores_count && i=scores_count || wscore>=score_buff[i]) ){ - fprintf(score_file,"%s : %ld\n",ENV_VAR_OR_USERNAME,wscore); + fprintf(tmp_score_file,"%s : %ld\n",ENV_VAR_OR_USERNAME,wscore); ret=i; wrote_it=1; } if(i