Merge pull request #4 from AMDmi3/highscore-handling

Fix highscore file handling
This commit is contained in:
Tiehuis 2014-09-13 09:28:28 +12:00
commit 5781fc6c16
3 changed files with 43 additions and 5 deletions

View File

@ -4,11 +4,11 @@ LIBS = -lcurses
all: 2048 all: 2048
2048: src/2048.c 2048: src/2048.c src/2048.h src/highscore_file.c
$(CC) $(CFLAGS) src/2048.c -o 2048 $(LIBS) $(CC) $(CFLAGS) src/2048.c src/highscore_file.c -o 2048 $(LIBS)
2048nc: src/2048_no_curses.c 2048nc: src/2048_no_curses.c src/2048.h src/highscore_file.c
$(CC) $(CFLAGS) src/2048_no_curses.c -o 2048nc $(CC) $(CFLAGS) src/2048_no_curses.c src/highscore_file.c -o 2048nc
clean: clean:
rm -f 2048 2048nc rm -f 2048 2048nc

View File

@ -1,6 +1,10 @@
#ifndef _2048_H_ #ifndef _2048_H_
#define _2048_H_ #define _2048_H_
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
typedef enum { typedef enum {
DIR_UP, DIR_UP,
DIR_RIGHT, DIR_RIGHT,
@ -8,6 +12,11 @@ typedef enum {
DIR_LEFT DIR_LEFT
} dir_t; } dir_t;
#define DATADIR_NAME "2048"
#define HIGHSCORE_FILE_NAME "highscore"
const char* get_highscore_file();
// Repeat an expression y, x times */ // Repeat an expression y, x times */
#define ITER(x, expr)\ #define ITER(x, expr)\
do {\ do {\
@ -38,7 +47,7 @@ typedef enum {
/* Constants */ /* Constants */
#define DEFAULT_GRID_SIZE 4 #define DEFAULT_GRID_SIZE 4
#define HISCORE_FILE ".hs2048g" #define HISCORE_FILE get_highscore_file()
#define USAGE_STR\ #define USAGE_STR\
"Usage:\n"\ "Usage:\n"\
" ./2048 [options]\n"\ " ./2048 [options]\n"\

29
src/highscore_file.c Normal file
View File

@ -0,0 +1,29 @@
#include "2048.h"
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <stdio.h>
const char* get_highscore_file() {
static char buffer[4096];
if (getenv("XDG_DATA_HOME") != NULL) {
snprintf(buffer, sizeof(buffer), "%s/%s/%s", getenv("XDG_DATA_HOME"), DATADIR_NAME, HIGHSCORE_FILE_NAME);
} else if (getenv("HOME") != NULL) {
snprintf(buffer, sizeof(buffer), "%s/.local/share/%s/%s", getenv("HOME"), DATADIR_NAME, HIGHSCORE_FILE_NAME);
} else {
return HIGHSCORE_FILE_NAME;
}
// create hierarrchy of directories up to highscore file location
char* sep = strrchr(buffer, '/');
while (sep != NULL) {
*sep = '\0';
if (strlen(buffer) != 0)
mkdir(buffer, 0777);
char* tmpsep = sep;
sep = strrchr(buffer, '/');
*tmpsep = '/';
}
return buffer;
}