【发布时间】:2011-03-02 12:02:42
【问题描述】:
如何在XCode 编辑器中使用C 语言获取Mac OS X 中的主目录路径。
【问题讨论】:
-
当前接受的答案无效,但还有另一个类似的问题尚未解决stackoverflow.com/questions/3726113/…
标签: c macos home-directory
如何在XCode 编辑器中使用C 语言获取Mac OS X 中的主目录路径。
【问题讨论】:
标签: c macos home-directory
这应该可以在 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;
}
【讨论】:
使用 FFSFindFolder:
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 字符。
【讨论】:
NSHomeDirectory 具有误导性。它实际上返回的是应用程序目录,而不是当前用户的 homedir。
CSCopyUserName() 不是查找用户主文件夹的解决方案。例如,它不会在 /Network/Users/leeg 找到我的。
#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;
}
【讨论】:
$ HOME=erased; ./app = 主目录已删除
getpwuid(),它返回密码结构,包括来自用户数据库的主目录。 developer.apple.com/mac/library/documentation/Darwin/Reference/…
HOME The system shall initialize this variable at the time of login to be a pathname of the user's home directory。请注意,该页面上还显示“如果在执行应用程序或实用程序期间环境中存在以下两节中的变量,则应赋予它们以下所述的含义。”。
/nonexistent)。可以说,任何故意更改其HOME 的人都希望应用程序继续将其视为其实际主目录。