Getting home directory in Mac OS X using C language

boom picture boom · Jun 11, 2010 · Viewed 11.3k times · Source

How can I get the path of home directory in Mac OS X using C language in XCode editor.

Answer

sorin picture sorin · Sep 17, 2010

This should work under Linux, Unix and OS X, for Windows you need to make a slight modification.

#include <stdlib.h>
#include <stdio.h>    
#include <pwd.h>
#include <unistd.h>

int main(void)
{
    const char *homeDir = getenv("HOME");

    if (!homeDir) {
        struct passwd* pwd = getpwuid(getuid());
        if (pwd)
           homeDir = pwd->pw_dir;
    }
    printf("Home directory is %s\n", homeDir);
    return 0;
}