How can I find the path to a file in an application bundle (NSBundle) using C?

五迷三道 提交于 2019-11-30 04:42:30

问题


Is there a C API for finding the path to a file in an application bundle?

I know that this can be done in Objective-C with the following syntax.

NSString *path = [[NSBundle mainBundle] pathForResource:@"MyImage" ofType:@"bmp"];

Is there a corresponding function that I can call from C or C++ code, as well?


回答1:


After Mike K pointed me in the right direction, I was able to retrieve the path to a file in an application bundle with the following code.

// Get a reference to the main bundle
CFBundleRef mainBundle = CFBundleGetMainBundle();

// Get a reference to the file's URL
CFURLRef imageURL = CFBundleCopyResourceURL(mainBundle, CFSTR("MyImage"), CFSTR("bmp"), NULL);

// Convert the URL reference into a string reference
CFStringRef imagePath = CFURLCopyFileSystemPath(imageURL, kCFURLPOSIXPathStyle);

// Get the system encoding method
CFStringEncoding encodingMethod = CFStringGetSystemEncoding();

// Convert the string reference into a C string
const char *path = CFStringGetCStringPtr(imagePath, encodingMethod);

fprintf(stderr, "File is located at %s\n", path);

This seems to be a bit longer than it needs to be, but at least it works!




回答2:


you can get the main bundle via:

CFBundleRef mainBundle = CFBundleGetMainBundle();

full details here:

http://developer.apple.com/library/mac/#documentation/CoreFOundation/Conceptual/CFBundles/AccessingaBundlesContents/AccessingaBundlesContents.html



来源:https://stackoverflow.com/questions/8768217/how-can-i-find-the-path-to-a-file-in-an-application-bundle-nsbundle-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!