Finding “~/Library/Application Support” from C++?

2020-06-09 06:40发布

I've written a GTKmm application and I'm trying to create some OS X enhancements. I'd like to store my configuration file in the Application Support/myApp folder, however, I can't figure out the proper way to locate this folder.

I've tried looking through the Core Foundation library (that I'm using to get my myApp.app path) but I can't find anything.

标签: c++ macos
3条回答
可以哭但决不认输i
2楼-- · 2020-06-09 07:15

Proper way to do it in C/C++:

#include <CoreServices/CoreServices.h>

FSRef ref;
OSType folderType = kApplicationSupportFolderType;
char path[PATH_MAX];

FSFindFolder( kUserDomain, folderType, kCreateFolder, &ref );

FSRefMakePath( &ref, (UInt8*)&path, PATH_MAX );

// You now have ~/Library/Application Support stored in 'path'

Naturally, those are very old APIs and their use is no longer recommended by Apple. Despite that it gets the job done if you want to avoid Objective-C completely in your codebase.

查看更多
beautiful°
3楼-- · 2020-06-09 07:15

It appears that the function to use for this is NSSearchPathForDirectoriesInDomains (or some other functions listed on the same page) with NSApplicationSupportDirectory as the argument.

查看更多
我只想做你的唯一
4楼-- · 2020-06-09 07:34

In BSD Unix, included in OS-X, you can get the home directory of the user running the program with this:

struct passwd *p = getpwuid(getuid());  /* defined in pwd.h, and requires sys/types.h */ 
char *home = p->pw_dir;

Using this, you can then construct the path using this in place of ~

char *my_app_name = "WHATEVER";
char app_support[MAXPATHLEN];  /* defined in sys/param.h */
snprintf(app_support,MAXPATHLEN,"%s/Library/Application Support/%s", home, my_app_name);
查看更多
登录 后发表回答