Get home directory in Linux

You need getuid to get the user id of the current user and then getpwuid to get the password entry (which includes the home directory) of that user:

#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>

struct passwd *pw = getpwuid(getuid());

const char *homedir = pw->pw_dir;

Note: if you need this in a threaded application, you’ll want to use getpwuid_r instead.

Leave a Comment