How can I programmatically detect what directory an executable is in when it is run?

I’ve been playing around with Command Line Tools in Xcode and I have stumbled upon something that I have no clue how to handle.

If I build my tool, and put the executable on the desktop, is it possible to run the executable and have the output be the directory that ‘self’ is in? Meaning, can I log ‘Hey I am in: /Users/me/Desktop’?

And then if I were to move that file elsewhere, have that change?

Is there some sort of environment variable I could use for this?


1 Solution

Ok, wow. Didn’t think I’d be able to find an answer this quick but here it is. Turns out that the location of the file is one of the arguments passed into main.

Here is the code:

    for (int i=0; i<argc; i++)
        NSLog(@"argv[%d] = '%s'", i, argv[i]);