objective-c - iOS:在c代码中获取文件路径

标签 objective-c ios c file file-io

我有一个 iOS 项目,我在其中使用了一些 C 源代码。 在 C 部分,我需要主包中文件的路径。 如何在不使用 Obj-C 的情况下获取它?

基本上我希望通过以下方式返回路径:

NSLog(@"%s",[[[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"] fileSystemRepresentation]);

最佳答案

所以只要像上面那样获取路径,然后得到一个C字符串版本:

NSString *path = [[[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"] fileSystemRepresentation];
char *cPath = [path cStringUsingEncoding:UTF8StringEncoding];

只要注意文档中的警告并复制字符串,如果你打算在你所在的方法/函数结束后继续使用它:

The returned C string is guaranteed to be valid only until either the receiver is freed, or until the current autorelease pool is emptied, whichever occurs first. You should copy the C string or use getCString:maxLength:encoding: if it needs to store the C string beyond this time.

更新:如果出于某种原因您不能使用 Foundation,您可以使用 Core Foundation 做类似的事情。您可以调用 CFBundleCopyResourceURL()(或其表亲之一)来获取资源的 URL,然后使用 CFURLCopyPath() 将其转换为路径。

关于objective-c - iOS:在c代码中获取文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13648763/

相关文章:

ios - 从 Autolayout 自动重构对象

iOS,reloadRowsAtIndexPaths - 在我将新对象添加到其数据源后崩溃

objective-c - iOS5:willSendRequestForAuthenticationChallenge 方法递归运行

ios - 我应该释放 NSData dataWithContentsOfURL 吗?

c - 调用fork()后子进程从哪里开始?

objective-c - 将Vision人脸检测VNFaceLandmarkRegion2D点转换为帧坐标以进行缩放

Objective-C 'RootViewController' 可能无法响应 xCode 中的 '-parseXMLFileAtURL:' 错误

objective-c - 为什么iOS模拟器会对此暂停?

c - 通过复制边值来填充矩阵

c - 如何让 callgrind 转储源代码行信息?