Expanding a leading tilde in C/C++

Published on . C/C++ userdir tilde

If you’re writing an app that accepts a path to a filename as user-input or in config-files, you’ll have to be able to parse the famous leading tilde and expand it to the correct home directory of the correct user. For example, if you want to access ~/.vimrc you need to expand the filepath to /home/david/.vimrc before you can do anything with it. You can use “word expansion” or wordexp to accomplish this.

Here’s a sample application showing how:

#include <stdio.h>
#include <wordexp.h>

int main(int argc, char* argv[]) {
  wordexp_t exp_result;
  wordexp(arv[1], &exp_result, 0);
  printf(exp_result.we_wordv[0]);
  wordfree(&exp_result);
}

Here are some of the results output by this app:

  • ~/.vimrc becomes /home/david/.vimrc
  • .vimrc stays .vimrc
  • ~blacky/.vimrc becomes /home/admin/blacky/.vimrc (blacky’s homedir is /home/admin/blacky)

The wordexp function can do a lot more, too, such as wildcard expansions. Check out the wordexp manpage for more info.

David Verhasselt

Senior full-stack engineer with 5 years of experience building web applications for clients all over the world.

Interested in working together?

Find out what I can do for you or get in touch!

Like this? Sign up to get regular updates