Code

utils os: Add sdb_realpath().
authorSebastian Harl <sh@tokkee.org>
Fri, 30 Jan 2015 12:42:27 +0000 (13:42 +0100)
committerSebastian Harl <sh@tokkee.org>
Fri, 30 Jan 2015 12:42:27 +0000 (13:42 +0100)
This function is similar to realpath() but also expands ~/ to the current
user's home directory.

src/include/utils/os.h
src/utils/os.c

index f4decde0f4b6312692c238d7d8cff2dc87165d36..42fdea3dad5e99872dc0eac03bc68cf3caa8a4e4 100644 (file)
@@ -47,6 +47,22 @@ extern "C" {
 char *
 sdb_get_homedir(void);
 
 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
 /*
  * sysdb_mkdir_all:
  * Recursively create the directory 'pathname' (similar to 'mkdir -p' on the
index e975f96e743b6510102426d6450dbe9270690e1c..c94e271be545dfe1bf51ec70d34887fc73ff3a19 100644 (file)
@@ -84,6 +84,29 @@ sdb_get_homedir(void)
        return strdup(result->pw_dir);
 } /* sdb_get_homedir */
 
        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)
 {
 int
 sdb_mkdir_all(const char *pathname, mode_t mode)
 {