Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", path);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...