How can I get the path of home directory in Mac OS X
using C
language in XCode
editor.
views:
242answers:
3
+5
A:
#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;
}
dreamlax
2010-06-11 04:27:32
`$ HOME=erased; ./app` = Home directory is erased
jweyrich
2010-06-11 05:13:03
As jweyrich says, this is not reliable. There's no guarantee that HOME is set to the home directory or that it is set at all. Server processes often delete their environment for security reasons. You should use `getpwuid()` which returns the password structure including the home directory from the user database. http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/getpwuid.3.html
JeremyP
2010-06-11 08:22:59
+6
A:
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.
drawnonward
2010-06-11 04:40:04
Note that `NSHomeDirectory` is misleading. It actually returns the application directory, not the current user homedir.
jweyrich
2010-06-11 05:26:15
@jweyrich that only applies to iPhone. On normal MacOS it is the equivalent of the others. None of these work on iPhone.
drawnonward
2010-06-11 08:42:57
@drawnonward Aye! Sorry, I thought it worked the same way. Thanks for correcting me.
jweyrich
2010-06-11 10:35:03
Note that `CSCopyUserName()` is _not_ a solution for finding a user's home folder. It won't find mine, for instance, which is at /Network/Users/leeg.
Graham Lee
2010-09-16 11:25:49
+1
A:
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>
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;
}
Sorin Sbarnea
2010-09-17 09:14:21