11

エディターで言語をMac OS X使用してホーム ディレクトリのパスを取得するにはどうすればよいですか。CXCode

4

3 に答える 3

14

これは、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;
}
于 2010-09-17T09:14:21.097 に答える
10

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 文字を使用できることに注意してください。

于 2010-06-11T04:40:04.613 に答える
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;
}
于 2010-06-11T04:27:32.480 に答える