Getting home directory in Mac OS X using C languag

2019-01-25 13:26发布

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

3条回答
仙女界的扛把子
2楼-- · 2019-01-25 13:41
#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;
}
查看更多
时光不老,我们不散
3楼-- · 2019-01-25 13:58

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

查看更多
再贱就再见
4楼-- · 2019-01-25 14:04

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.

查看更多
登录 后发表回答