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 programmatic
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
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;
}
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;
}