From 92b88ad62cefc6aa9029906eccdbdf8643ec8914 Mon Sep 17 00:00:00 2001 From: Sebastian Harl Date: Fri, 30 Jan 2015 13:42:27 +0100 Subject: [PATCH] utils os: Add sdb_realpath(). This function is similar to realpath() but also expands ~/ to the current user's home directory. --- src/include/utils/os.h | 16 ++++++++++++++++ src/utils/os.c | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/include/utils/os.h b/src/include/utils/os.h index f4decde..42fdea3 100644 --- a/src/include/utils/os.h +++ b/src/include/utils/os.h @@ -47,6 +47,22 @@ extern "C" { char * sdb_get_homedir(void); +/* + * sdb_realpath: + * Returns the canonicalized absolute pathname for the specified path. The + * function expands all symbolic links and resolves references to '.', '..', + * and extra slash characters (/). + * + * '~/' at the start of the string will be replaced by the current user's home + * directory. + * + * Returns: + * - the canonicalized absolute pathname on success + * - NULL else + */ +char * +sdb_realpath(const char *path); + /* * sysdb_mkdir_all: * Recursively create the directory 'pathname' (similar to 'mkdir -p' on the diff --git a/src/utils/os.c b/src/utils/os.c index e975f96..c94e271 100644 --- a/src/utils/os.c +++ b/src/utils/os.c @@ -84,6 +84,29 @@ sdb_get_homedir(void) return strdup(result->pw_dir); } /* sdb_get_homedir */ +char * +sdb_realpath(const char *path) +{ + if (! path) + return NULL; + + if ((strlen(path) >= 2) && (path[0] == '~') && (path[1] == '/')) { + char *homedir = sdb_get_homedir(); + char tmp[(homedir ? strlen(homedir) : 0) + strlen(path)]; + char *ret; + + if (! homedir) + return NULL; + + snprintf(tmp, sizeof(tmp), "%s/%s", homedir, path + 2); + ret = realpath(tmp, NULL); + free(homedir); + return ret; + } + + return realpath(path, NULL); +} /* sdb_realpath */ + int sdb_mkdir_all(const char *pathname, mode_t mode) { -- 2.30.2