Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode loading program resources from my Home folder rather than Resources - C++

This is my first time using Xcode and it is appalling to me how completely non intuitive this IDE is. I heard it was better in the past and I really hope it was.

My problem is that the resources my program loads, a data file and an .ini file, it automatically searches for these file in my Home folder. I want for it to search for these files in the Resource folder of the .app. I am using C++ and all of the examples I have found are for Objective-C.

Any idea on how to fix this?

like image 868
Satchmo Brown Avatar asked Jul 13 '26 09:07

Satchmo Brown


1 Answers

You are probably assuming that, when your app launches, the current working directory of the process is your app's bundle. It isn't. (Nothing to do with Xcode particularly -- that's just how OS X works.)

Typically you would use NSBundle (Objective-C) or CFBundle (C) to find resources in your app bundle. Since you're using C++, let's use the C API.

To find the URL to a file "myFile.ini" in the Resources directory in your app bundle:

CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef url = CFBundleCopyResourceURL(mainBundle, CFSTR("myFile"), CFSTR("ini"), NULL);
UInt8 filePath[PATH_MAX];
if (CFURLGetFileSystemRepresentation(url, true, filePath, sizeof(filePath)))
{
    // use your API of choice to open and read the file at filePath
}

Or, to just change the CWD to your app bundle:

CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef url = CFBundleCopyBundleURL(mainBundle);
UInt8 bundlePath[PATH_MAX];
if (CFURLGetFileSystemRepresentation(url, true, bundlePath, sizeof(bundlePath)))
{
    if (chdir((const char*)bundlePath) == 0)
    {
        // now the CWD is your app bundle, and you can use relative path names to access files inside it
    }
}
like image 184
Kurt Revis Avatar answered Jul 15 '26 02:07

Kurt Revis