Object-C调用C函数来读取文件

时间:2013-04-28 21:28:47

标签: iphone ios objective-c c

我正在开发一个iPhone项目,我需要调用一些C函数,这些函数位于像myfile.c这样的C文件中。我可以在其中调用一些函数。但是当我需要在C文件中打开一个文件时。我得到了糟糕的访问权限(gdb)。我想要读取的文件已放在项目文件夹中并导入到项目中。 甚至,我无法在C函数中创建一个新文件。 有人可以帮我一把吗?非常感谢你。

2 个答案:

答案 0 :(得分:1)

在iOS中使用C函数和文件时,不能这样做

readFunction("filename.txt");

您必须将路径(例如捆绑包中的文件)设置为此

readFunction([[NSBundle mainBundle] pathForResource:@"filename" ofType:@"txt"].UTF8String);

并为写作做同样的事,例如

NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docsDir stringByAppendingPathComponent:@"filename.txt"];
writeFunction(filePath.UTF8String);

答案 1 :(得分:1)

正如Chris Loonam所说,你无法通过文件名访问文件是iOS - 你需要使用 - [NSBundle pathForResource:ofType:]来获取完整的文件名。

要从C执行此操作,您需要以下内容:

void testFunction(char* fileName) 
{
    NSString* fName = [NSString stringWithUTF8String: fileName];
    NSString* fullPath = [[NSBundle mainBundle] pathForResource: fName ofType: @""];

    const char* cFullPath = [fullPath cStringUsingEncoding: NSUTF8StringEncoding];

    //do something with cFullPath
}

不幸的是,由于你在这里使用的是Objective-C函数,你需要将文件重命名为.m而不是.c - 除此之外,它可以是普通的C源文件!