void HighScoresInit(void) { CArrayInit(&HighScores, sizeof(HighScore)); char buf[MAX_PATH]; get_user_config_file(buf, MAX_PATH, HIGH_SCORE_FILE); if (strlen(buf) == 0) { printf("Error: cannot find config file path\n"); return; } FILE *f = fopen(buf, "r"); if (f == NULL) { printf("Error: cannot open config file %s\n", buf); return; } while (fgets(buf, sizeof buf, f)) { HighScore hs; struct tm tm; sscanf( buf, "%d %04d-%02d-%02d %02d:%02d:%02d", &hs.Score, &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour, &tm.tm_min, &tm.tm_sec); // Time correction tm.tm_year -= 1900; tm.tm_mon--; hs.Time = mktime(&tm); CArrayPushBack(&HighScores, &hs); } fclose(f); }
void HighScoresAdd(const int s) { // Find the right position to add the score // Scores are in descending order HighScore hsNew; hsNew.Score = s; hsNew.Time = time(NULL); bool inserted = false; for (int i = 0; i < (int)HighScores.size; i++) { const HighScore *hs = CArrayGet(&HighScores, i); if (hs->Score <= s) { CArrayInsert(&HighScores, i, &hsNew); inserted = true; break; } } if (!inserted) { CArrayPushBack(&HighScores, &hsNew); } // Save to file char buf[MAX_PATH]; get_user_config_file(buf, MAX_PATH, HIGH_SCORE_FILE); if (strlen(buf) == 0) { printf("Error: cannot find config file path\n"); return; } FILE *f = fopen(buf, "w"); if (f == NULL) { printf("Error: cannot open config file %s\n", buf); return; } for (int i = 0; i < MIN((int)HighScores.size, MAX_HIGH_SCORES); i++) { const HighScore *hs = CArrayGet(&HighScores, i); struct tm *ptm = gmtime(&hs->Time); strftime(buf, sizeof buf, "%Y-%m-%d %H:%M:%S", ptm); fprintf(f, "%d %s\n", hs->Score, buf); } fclose(f); }
//! locate config file and load it static index_error load_config ( index_data_t* index_data_ ) { dbg_message (__func__); FILE *fp; char cfg_file[MAX_PATH*2]; for (;;) { // we assume following cases: // - if a config file is present in current directory, we use that one fp = fopen (APP_INI_FILE, "r"); if ( fp != NULL ) { memcpy (cfg_file, APP_INI_FILE, sizeof(APP_INI_FILE)); break; } // - if a file is present in config directory, use that get_user_config_file (cfg_file, sizeof(cfg_file), APP_NAME); if (cfg_file[0] == 0) break; fp = fopen (cfg_file, "r"); if ( fp != NULL ) break; // - gave up break; } // load the file if present if ( fp != NULL ) { dbg_message ("loading config file %s", cfg_file); if ( ini_parse (cfg_file, handler, index_data_) < 0 ) { fprintf (stderr, "Can't load configuration file %s\n", cfg_file); return FUNC_GENERIC_ERROR; } } else { dbg_message ("no config file to load" ); } return FUNC_OK; }