From 957ef4d81438a74d530f2a3890bfcd0145c11fd9 Mon Sep 17 00:00:00 2001 From: Jesse Luehrs Date: Sun, 1 May 2016 22:21:46 -0400 Subject: simplify --- src/config.c | 32 ++++++++++++++------------------ src/util.c | 19 +++++++++++++++++++ src/util.h | 1 + 3 files changed, 34 insertions(+), 18 deletions(-) diff --git a/src/config.c b/src/config.c index b314522..7030b78 100644 --- a/src/config.c +++ b/src/config.c @@ -317,46 +317,42 @@ static void runes_config_set_defaults(RunesTerm *t) static FILE *runes_config_get_config_file() { char *home, *config_dir, *path; - size_t home_len, config_dir_len; FILE *file; home = getenv("HOME"); - home_len = strlen(home); config_dir = getenv("XDG_CONFIG_HOME"); if (config_dir) { config_dir = strdup(config_dir); } else { - config_dir = malloc(home_len + sizeof("/.config") + 1); - strcpy(config_dir, home); - strcpy(config_dir + home_len, "/.config"); + sprintf_dup(&config_dir, "%s/.config", home); } - config_dir_len = strlen(config_dir); - path = malloc(config_dir_len + sizeof("/runes/runes.conf") + 1); - strcpy(path, config_dir); - strcpy(path + config_dir_len, "/runes/runes.conf"); + sprintf_dup(&path, "%s/runes/runes.conf", config_dir); free(config_dir); - if ((file = fopen(path, "r"))) { - free(path); + file = fopen(path, "r"); + free(path); + + if (file) { return file; } + sprintf_dup(&path, "%s/.runesrc", home); + + file = fopen(path, "r"); free(path); - path = malloc(home_len + sizeof("/.runesrc") + 1); - strcpy(path, home); - strcpy(path + home_len, "/.runesrc"); - if ((file = fopen(path, "r"))) { - free(path); + if (file) { return file; } - free(path); + path = "/etc/runesrc"; + + file = fopen(path, "r"); - if ((file = fopen("/etc/runesrc", "r"))) { + if (file) { return file; } diff --git a/src/util.c b/src/util.c index d87fd72..686f02d 100644 --- a/src/util.c +++ b/src/util.c @@ -1,5 +1,6 @@ #include #include +#include #include "runes.h" @@ -11,3 +12,21 @@ void runes_warn(const char *fmt, ...) vfprintf(stderr, fmt, ap); va_end(ap); } + +int sprintf_dup(char **out, const char *fmt, ...) +{ + int outlen = 0; + va_list ap; + + va_start(ap, fmt); + outlen = vsnprintf(*out, outlen, fmt, ap); + va_end(ap); + + *out = malloc(outlen + 1); + + va_start(ap, fmt); + outlen = vsnprintf(*out, outlen + 1, fmt, ap); + va_end(ap); + + return outlen; +} diff --git a/src/util.h b/src/util.h index 183f8c5..9432ed1 100644 --- a/src/util.h +++ b/src/util.h @@ -4,5 +4,6 @@ #define UNUSED(x) ((void)x) void runes_warn(const char *fmt, ...); +int sprintf_dup(char **out, const char *fmt, ...); #endif -- cgit v1.2.3