views:

242

answers:

3

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

+5  A: 
#include <stdlib.h>
#include <stdio.h>    

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

    if (homeDir)
        printf("Home directory is %s\n", homeDir);
    else
        printf("Couldn't figure it out.\n");

    return 0;
}
dreamlax
`$ HOME=erased; ./app` = Home directory is erased
jweyrich
As jweyrich says, this is not reliable. There's no guarantee that HOME is set to the home directory or that it is set at all. Server processes often delete their environment for security reasons. You should use `getpwuid()` which returns the password structure including the home directory from the user database. http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/getpwuid.3.html
JeremyP
+6  A: 

with FSFindFolder:

UInt8 path[1024];
FSRef file;
FSFindFolder( kOnAppropriateDisk , kCurrentUserFolderType , kCreateFolder , &file );
FSRefMakePath( &file , path , sizeof(path) );

with CSCopyUserName:

char path[1024];
CFStringRef name = CSCopyUserName( true );
CFStringRef full = CFStringCreateWithFormat( NULL , NULL , CFSTR( "/Users/%@" ) , name );
CFStringGetCString( full , path , sizeof(path) , kCFStringEncodingUTF8 );
// release strings

with NSHomeDirectory:

char path[1024];
CFStringGetCString( (CFStringRef)NSHomeDirectory() , path , sizeof(path) , kCFStringEncodingUTF8 );

note that the path can use UTF8 characters.

drawnonward
Note that `NSHomeDirectory` is misleading. It actually returns the application directory, not the current user homedir.
jweyrich
@jweyrich that only applies to iPhone. On normal MacOS it is the equivalent of the others. None of these work on iPhone.
drawnonward
@drawnonward Aye! Sorry, I thought it worked the same way. Thanks for correcting me.
jweyrich
Note that `CSCopyUserName()` is _not_ a solution for finding a user's home folder. It won't find mine, for instance, which is at /Network/Users/leeg.
Graham Lee
+1  A: 

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>

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;
}

Sorin Sbarnea