Skip to content
This repository has been archived by the owner on May 18, 2024. It is now read-only.

Commit

Permalink
Fix highscore file handling
Browse files Browse the repository at this point in the history
Don't create highscore file in the current directory, instead
create in under $XDG_DATA_HOME/2048/highscore or
$HOME/.local/share/2048/highscore as modern apps should.
  • Loading branch information
AMDmi3 committed Sep 12, 2014
1 parent 37c1d36 commit f2aa753
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 5 deletions.
8 changes: 4 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ LIBS = -lcurses

all: 2048

2048: src/2048.c
$(CC) $(CFLAGS) src/2048.c -o 2048 $(LIBS)
2048: src/2048.c src/2048.h src/highscore_file.c
$(CC) $(CFLAGS) src/2048.c src/highscore_file.c -o 2048 $(LIBS)

2048nc: src/2048_no_curses.c
$(CC) $(CFLAGS) src/2048_no_curses.c -o 2048nc
2048nc: src/2048_no_curses.c src/2048.h src/highscore_file.c
$(CC) $(CFLAGS) src/2048_no_curses.c src/highscore_file.c -o 2048nc

clean:
rm -f 2048 2048nc
11 changes: 10 additions & 1 deletion src/2048.h
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
#ifndef _2048_H_
#define _2048_H_

#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>

typedef enum {
DIR_UP,
DIR_RIGHT,
DIR_DOWN,
DIR_LEFT
} dir_t;

#define DATADIR_NAME "2048"
#define HIGHSCORE_FILE_NAME "highscore"

const char* get_highscore_file();

// Repeat an expression y, x times */
#define ITER(x, expr)\
do {\
Expand Down Expand Up @@ -38,7 +47,7 @@ typedef enum {

/* Constants */
#define DEFAULT_GRID_SIZE 4
#define HISCORE_FILE ".hs2048g"
#define HISCORE_FILE get_highscore_file()
#define USAGE_STR\
"Usage:\n"\
" ./2048 [options]\n"\
Expand Down
29 changes: 29 additions & 0 deletions src/highscore_file.c
Original file line number Diff line number Diff line change
@@ -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;
}

0 comments on commit f2aa753

Please sign in to comment.