Finding out executable location from a c program

Clark Cox clarkcox3 at gmail.com
Mon Nov 19 18:09:36 PST 2007


On Nov 19, 2007 2:55 PM, Scott Stevenson <sstevenson at mac.com> wrote:
>
> On Nov 19, 2007, at 8:51 AM, Christiaan Hofman wrote:
>
> >> I can't think of a way of doing it. It's normal practise to put
> >> support files in a location like /usr/local/lib or similar rather
> >> than with the executable on Unix. On a Mac the solution is normally
> >> to package it inside the app bundle and use the API to access that.
> >
> > I also wouldn't know. There should be a way though, as internally
> > NSBundle does.
>
> I believe CFBundle is open source.

Why bother with CFBundle's source? Just *use* CFBundle. (composed in
e-mail, but should give a basic idea):

#include <CoreFoundation/CFBundle.h>
#include <stdlib.h>
#include <stdio.h>

char *GetExecutableLocation() {
    CFBundleRef bundle          = CFBundleGetMainBundle();
    CFURLRef    executableURL   = CFBundleCopyExecutableURL(bundle);
    CFStringRef executablePath  =
CFURLCopyFileSystemPath(executableURL, kCFURLPOSIXPathStyle);
    CFIndex     maxLength       =
CFStringGetMaximumSizeOfFileSystemRepresentation(executablePath);
    char        *result         = malloc(maxLength);

    if(result) {
        if(!CFStringGetFileSystemRepresentation(executablePath,
result, maxLength)) {
            free(result);
            result = NULL;
        }
    }

    CFRelease(executablePath);
    CFRelease(executableURL);

    return result;
}


int main() {
    char    *path   = GetExecutableLocation();
    printf("path = \"%s\"\n", path);
    free(path);

    return 0;
}



int main() {
    char    *path   = GetExecutableLocation();
    printf("path = \"%s\"\n", path);
    free(path);

    return 0;
}


-- 
Clark S. Cox III
clarkcox3 at gmail.com


More information about the MacOSX-dev mailing list