简体   繁体   English

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

[英]Getting home directory in Mac OS X using C language

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

This should work under Linux, Unix and OS X, for Windows you need to make a slight modification. 这应该适用于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;
}

with FSFindFolder: 使用FSFindFolder:

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

with CSCopyUserName: 使用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: 与NSHomeDirectory:

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

note that the path can use UTF8 characters. 请注意该路径可以使用UTF8字符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM