The iPhone SDK docs claim fopen() is a supported method of file access but I am unable to get it to return a FILE handle. I am accessing a directory which is included in my project. I have tried fopen "filename","dir/filename","./filename","./dir/filename","/dir/filename" all returning with a null pointer. Some people report using it with no issue so I am sure it is something simple!
Asked
Active
Viewed 1.8k times
2 Answers
23
Just to be clear to open a file "some.txt"...
NSString * path = [[NSBundle mainBundle] pathForResource: @"some" ofType: @"txt"];
FILE *f = fopen([path cStringUsingEncoding:1],"r");
if (f == NULL) NSLog([path stringByAppendingString:@" not found"]);

Nick Van Brunt
- 15,244
- 11
- 66
- 92
-
Nice answer, How to see the contents of audio after opening. – Warrior Oct 22 '10 at 05:36
-
3In stead of `[path cStringUsingEncoding:1]` you can also use `path.UTF8String` – codingFriend1 Oct 25 '12 at 14:18
22
if you're trying to access a file within your application bundle, you need to get the full path to it: [[NSBundle mainBundle] pathForResource: FILENAME ofType: FILEEXTENSION]
This returns an NSString, which you can pull a UTF8String out of and pass to fopen.

bobobobo
- 64,917
- 62
- 258
- 363

Ben Gottlieb
- 85,404
- 22
- 176
- 172