From: Sebastian Harl Date: Fri, 30 Jan 2015 12:42:27 +0000 (+0100) Subject: utils os: Add sdb_realpath(). X-Git-Tag: sysdb-0.7.0~31 X-Git-Url: https://git.tokkee.org/?a=commitdiff_plain;h=92b88ad62cefc6aa9029906eccdbdf8643ec8914;p=sysdb.git utils os: Add sdb_realpath(). This function is similar to realpath() but also expands ~/ to the current user's home directory. --- 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) {