Alex B
Alex B

Reputation: 84822

What's the equivalent of SHGetFolderPath on OSX?

I am porting a Windows application to OSX and need to get user's home, documents and music directories. It is done on Windows using a SHGetFolderPath WinAPI call.

  1. How can I do it in OSX, preferably without resorting to Objective C?
  2. If I can't do it without Objective C, how can I do it at all?

Upvotes: 2

Views: 526

Answers (3)

Ryan
Ryan

Reputation:

I know you'd prefer to not use Objective-C, but here is an example of how to do it with Objective-C:

static NSString *PathForUserDirectory(NSSearchPathDirectory directory) {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);
    if ([paths count] > 0) {
        return [paths objectAtIndex:0];
    }
    return nil;
}

Use it like this:

NSLog(@"Library folder: %@", PathForUserDirectory(NSLibraryDirectory));

which will print the full POSIX path of the current user's library directory. Here is a reference for other directories you can search for:

NSSearchPathDirectory

Upvotes: 3

Adam Batkin
Adam Batkin

Reputation: 52994

You can get a user's own home directory by looking at the environment variable HOME (for example, "echo $HOME" from a shell or getenv from C). For the home directory of other users, you can use getpwnam or getpwuid (see their manpages for more details) to retrieve their home directory. For other directories, you can try the Carbon API FSFindFolder.

Upvotes: 3

Rob Kennedy
Rob Kennedy

Reputation: 163277

Call NSSearchPathForDirectoriesInDomains or FSFindFolder.

Upvotes: 2

Related Questions