使用fopen()在.bundle中打开文件

时间:2014-11-04 22:13:38

标签: ios frameworks bundle fopen resourcebundle

我已经构建了一个自定义框架和随附的资源包,以便在其他项目中使用。资源包包括各种.sqlite和.bin文件。我正在尝试使用我的框架在另一个项目中打开.bin文件但没有成功。

我们说我的捆绑包名为 CustomFramework.bundle 。我的框架中有一个类 ResourceHelper.cpp ,它正在尝试打开位于 CustomFramework.bundle 中的 mybin.bin

以下是我目前正在尝试打开它的方式:

void ResourceHelper::openBinFromResourceFolder(FILE **file) {
    std::string path;
    path = "CustomFramework.bundle/";
    path.append("mybin.bin");
    *file = fopen(path.c_str(), "rb");
}
在此fopen()调用之后,

file NULL

我想如何在我的.bundle中打开.bin文件?

由于

1 个答案:

答案 0 :(得分:1)

原则上你必须得到主束字符串并将资源包附加到该字符串。以下是我的工作方式。

void ResourceHelper::openBinFromResourceFolder(const char *binName, FILE **file) {
    std::string path;
    // split bin name into name and file type (bin)
    std::string binStr = binName;
    std::size_t pos = binStr.find(".");
    std::string filename = binStr.substr(0, pos);
    std::string type = binStr.substr(pos+1);

    // get bundle and CFStrings
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFStringRef cf_resource_path = CFStringCreateWithCString(NULL, resourcePath_.c_str(), kCFStringEncodingUTF8);
    CFStringRef cf_filename = CFStringCreateWithCString(NULL, filename.c_str(), kCFStringEncodingUTF8);
    CFStringRef cf_file_type = CFStringCreateWithCString(NULL, type.c_str(), kCFStringEncodingUTF8);
    CFURLRef url_resource = CFBundleCopyResourceURL(mainBundle, cf_filename, cf_file_type, cf_resource_path);
    CFStringRef urlString = CFURLCopyFileSystemPath(url_resource, kCFURLPOSIXPathStyle);
    path = CFStringGetCStringPtr(urlString, kCFStringEncodingUTF8);

    *file = fopen(path.c_str(), "rb");
}