Search code examples
c++macosterminalexecutableworking-directory

How to set the working directory of an executable program in Mac OSX


I created a C++ project in Xcode which successfully builds and runs a program in the Xcode environment. This program is dependent on existing in its current working directory to access several files. Outside of the Xcode environment, when I double-click on the executable file, I get a message that notifies me that the terminal exits the current working directory.

The current working directory exiting twice [1]: https://i.sstatic.net/EZ5kc.png

After the exit messages, my current working directory results in /Users/chefjeff/

Judging by this other post: How to change default working directory on Mac OS X?

There might not be an easy solution to double-clicking an executable so that it opens in its current directory, but I still need a solution to using the GUI on Mac in some sort of way to open the file in its working directory.

EDIT:

The project folder, CultGame, must be able to exist at any location in the user's filesystem and still have its packaged files and executable files work.


Solution

  • So here's how I solved this:

    I couldn't change the default directory that double-clicking on the program to run it would start up on.

    1. I can use the chdir() function to move around directories. I moved to the root directory using chdir() after the program began and started me in Users/Username. More on chdir here: https://www.geeksforgeeks.org/chdir-in-c-language-with-examples/
    2. I used _NSGetExecutablePath() to get the directory that the currently executing file is located in. More on that here: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/dyld.3.html
    3. From root, I used chdir() to navigate to the path of the currently executing file which I obtained with _NSGetExecutablePath().

    I will update my answer in a bit with a code example. Hopefully this helps!