开发者

How to find the residing directory of a OS X application package - programmatically

I have a OS X application as a .app package which can reside in any arbitrary location in the filesystem. Is there a way to find the current path of the package programmatically from with.

NOTE

getcwd() doesn't work since the current directory of all packages opened is via click-open or using the open command is "/" . If i invoke the executabl开发者_如何转开发e from myapp.app/Contents/MacOS , the directory is shown correctly. It is a cocoa application.

Any clues?


You should be able to find the location of the .app by [[NSBundle mainBundle] bundleURL]; or [[NSBundle mainBundle] bundlePath];.

However, you probably want to access resources inside the .app by going through NSBundle to locate them in most cases (this deals with issues like localization).

Note: If you are planning to modify the application bundle; don't. You should not, can not and must not assume that you have write access to the application bundle; and if you do, something is likely very wrong.

Edit: As a point of interest, if you are writing a C program on OS X and need to find the location of the executable; you can use a non-portable main declaration like so:

int main (int argc, const char *argv[], const char *env[], const char *path[]) {
  // path[0] now contains the path to the executable
  // NOT PORTABLE! OS X ONLY!
  return 0;
}


Building off the argv[0] version above, you can also get the path from:

    NSArray* arguments = [[NSProcessInfo processInfo] arguments];

    NSString* exe = [args objectAtIndex:0];

from init or applicationDidFinishLaunching


The bundle directory might be a problem with command line tools. So i use the following function which uses the mach-0 linker function to resolve shared libraries.

 static char* find_executable_filepath () noexcept 
 {
     char path[1];
     uint32_t size = 1;
     if (_NSGetExecutablePath(path, &size) == 0) return nullptr;
     char* res = (char*)malloc(size+1);
     if (_NSGetExecutablePath(res, &size) != 0) return nullptr;
     char* r = realpath(res, nullptr);
     free(res);
     return r; 
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜