Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting home directory in Mac OS X using C language

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

like image 833
boom Avatar asked Jun 11 '10 04:06

boom


1 Answers

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;
}
like image 108
sorin Avatar answered Sep 21 '22 21:09

sorin