使用C语言在Mac OS X中获取主目录

时间:2010-06-11 04:25:28

标签: c macos home-directory

如何在Mac OS X编辑器中使用C语言在XCode中获取主目录的路径。

3 个答案:

答案 0 :(得分:12)

这应该适用于Linux,Unix和OS X,对于Windows,您需要稍作修改。

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

答案 1 :(得分:8)

使用FSFindFolder:

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

使用CSCopyUserName:

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

使用NSHomeDirectory:

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

请注意,该路径可以使用UTF8字符。

答案 2 :(得分:6)

#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;
}
相关问题