+char *
+expand_tilde(char *s)
+{
+ struct passwd *pwd;
+ int i;
+ char user[LOGIN_NAME_MAX];
+ const char *sc = s;
+ char *result;
+
+ if (s == NULL)
+ errx(1, "expand_tilde: NULL string.");
+
+ if (s[0] != '~') {
+ result = strdup(sc);
+ goto out;
+ }
+
+ ++s;
+ for (i = 0; s[i] != '/' && s[i] != '\0'; ++i)
+ user[i] = s[i];
+ user[i] = '\0';
+ s = &s[i];
+
+ pwd = strlen(user) == 0 ? getpwuid(getuid()) : getpwnam(user);
+ if (pwd == NULL)
+ result = strdup(sc);
+ else
+ if (asprintf(&result, "%s%s", pwd->pw_dir, s) == -1)
+ result = NULL;
+out:
+ if (result == NULL)
+ errx(1, "expand_tilde: failed to allocate memory.");
+
+ return result;
+}
+