Relative Paths Not Working in Xcode C++

Solution 1:

Took me about 5 hours of Google and trying different things to FINALLY find the answer!

#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#endif

// ----------------------------------------------------------------------------
// This makes relative paths work in C++ in Xcode by changing directory to the Resources folder inside the .app bundle
#ifdef __APPLE__    
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
    char path[PATH_MAX];
    if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
    {
        // error!
    }
    CFRelease(resourcesURL);

    chdir(path);
    std::cout << "Current Path: " << path << std::endl;
#endif
// ----------------------------------------------------------------------------

I've thrown some extra include guards because this makes it compile Apple only (I develop cross platform) and makes the code nicer.

I thank the other 2 guys for your answers, your help ultimately got me on the right track to find this answer so i've voted you both up. Thanks guys!!!!

Solution 2:

Do not depend on the current working directory in binary code. Just don't. You cannot trust the operating system or shell to set it to where you expect it to be set, on Mac, Windows, or Unix.

For straight C, use _NSGetExecutablePath in dyld.h to get the path to your current executable, then you can go relative from there.

If you're just experimenting and want it to work, in Xcode choose Project > Edit Active Executable, and there's a panel there in which you can set the initial working directory to the project directory, the executable's parent directory, or any arbitrary directory. This should only be used for testing purposes. In the Mac OS, when you write a real app and launch it from the Finder, the working directory is /. And for Unix apps you have no control whatsoever over what the working directory is.