chdir() to home directory

darksky picture darksky · Feb 29, 2012 · Viewed 30.9k times · Source

I am using the chdir() C function to allow a user to change directory.

The function however, doesn't recognize '~'. Do I need to do any explicit conversion, so chdir doesn't recognize what ~ means? Because mine isn't working. Or am I doing something wrong?

Answer

Ernest Friedman-Hill picture Ernest Friedman-Hill · Feb 29, 2012

Tilde expansion is handled by the shell, not by a system call. You could use getenv() to read the environment variable HOME and then use that as the argument to chdir().

There are system calls to get this information that may be more reliable on an individual system, but they're not completely portable. Look, for example, at getpwuid().