Expanding a leading tilde in C/C++

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 I enter “~/.vimrc” it needs to be expanded to the file in my userdir “/home/david/.vimrc” before you can do anything with it. You can use “word expand” 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]);
}

That should pretty much tell you everything you need to know. Here are some of the results output by this app:

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

As you can see, it handles pretty much every situation correctly.

This entry was posted in Code Poetry, How To and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">