Jakob
Jakob

Reputation: 1146

iOS: Obtaining path of file in c code

I am having an iOS Project in which i use some C-Sources. In the C part I need the path to a file in the mainbundle. How can I obtain it without using Obj-C?

Basically I want to have the path returned by:

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

Upvotes: 0

Views: 384

Answers (2)

Caleb
Caleb

Reputation: 124997

So just get the path as you did above, and then get a C string version:

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

Just pay attention to the warning in the docs and copy the string if you plan to hang onto it beyond the end of the method/function that you're in:

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.

Update: If for whatever reason you can't use Foundation, you can do something similar using Core Foundation. You can call CFBundleCopyResourceURL() (or one of its cousins) to get the URL for the resource, and then convert that to a path using CFURLCopyPath().

Upvotes: 2

AlexWien
AlexWien

Reputation: 28727

Best you read the path with objective-c and pass it as char * to the c class by calling a function.
You further could asign a global variable char * which is visible for both objective-c and C.

Upvotes: 1

Related Questions