c++ - Xcode 从我的主文件夹而不是资源加载程序资源 - C++

标签 c++ xcode resources

这是我第一次使用 Xcode,这个 IDE 完全不直观让我感到震惊。我听说过去更好,我真的希望如此。

我的问题是我的程序加载的资源,一个数据文件和一个 .ini 文件,它会自动在我的主文件夹中搜索这些文件。我想让它在 .app 的 Resource 文件夹中搜索这些文件。我正在使用 C++,我找到的所有示例都是针对 Objective-C 的。

知道如何解决这个问题吗?

最佳答案

您可能会假设,当您的应用程序启动时,进程的当前工作目录就是您的应用程序包。它不是。 (与 Xcode 无关——这就是 OS X 的工作方式。)

通常您会使用 NSBundle ( objective-c )或 CFBundle (C) 在您的应用程序包中查找资源。由于您使用的是 C++,因此让我们使用 C API。

要在您的应用程序包的资源目录中找到文件“myFile.ini”的 URL:

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
}

或者,只需将 CWD 更改为您的应用程序包:

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
    }
}

关于c++ - Xcode 从我的主文件夹而不是资源加载程序资源 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9765925/

相关文章:

c++ - 在 C++ 中确定模板类型的取值范围

c++ - 从函数返回 unique_ptr

ios - 为什么 func 闭包有时会在 Swift 中删除它的参数名称?

Android strings.xml 最佳实践?

qt - 在 Linux Qt 上使用相对路径读取文件

c++ - try/catch block 中的完整代码

c++ - 如何定义一个可以保存 uintptr_t 或 uint32_t 而无需 union 的类型?

ios - 我正在尝试 JSON 解码(Swift)

ios - 选择 Carthage 依赖的部署目标

asp.net - 在资源文件中使用 HTML