Question

I'm running a GLFW app (that I wrote in C++)

I run it as follows:

./prog.app/Contents/MacOS/prog # from the command line

However, my code can't read relative-pathed files properly.

So I believe what's happening is that this Mac Bundle is changing my current directory.

1) what does it change it to? 2) can I control this?

Thanks!

Was it helpful?

Solution

Never make any assumptions about the current working directory when your app is launched. The Finder is reasonably consistent about this but it is not the only way to launch an app. When debugging under Xcode for example the initial working directory will be different, and there are various other methods which may or may not set the working directory as expected. You should test your app by launching it from the command line in a totally unrelated directory - if it still finds its files under this condition then you're in good shape.

OTHER TIPS

You may be able to use this piece of code to find out the location of prog.

#include <mach-o/dyld.h>

char exe_path[MAXPATHLEN];
char link_path[MAXPATHLEN];

uint32_t size = sizeof(exe_path);
if (_NSGetExecutablePath(exe_path, &size) != 0)
    assert();

if (realpath(exe_path, link_path) == 0)
    assert();

return link_path; 

Frequently it's the user's home directory. I'm not sure if that's guaranteed, but you can use chdir() inside Cocoa apps. Depending on your requirements, users may have a better experience if you use filesystem bookmarks (10.6+) or aliases (earlier). Or even absolute paths, which are still robust against changing working directory.

If you look at the GLFW sources, you'll see that on OSX during init it explicitly changes the current directory. Look here and scroll down to about line 236 (or search for chdir).

I found your SO question because I'm currently trying to understand why GLFW does an explicit chdir during init. I discovered this because I have a program that works on all platforms except OSX. On OSX it can't find it's data files using a relative path. My temporary solution is to get the current directory when main starts and reset the current directory after initializing GLFW.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top