Reputation: 1869
Reading text file with NSString:stringWithContentsOfFile?
NSString *txtFilePath = [[NSBundle mainBundle] pathForResource:@"\help" ofType:@"txt"];
NSString *txtFileContents = [NSString stringWithContentsOfFile:txtFilePath encoding:NSUTF8StringEncoding error:NULL];
NSLog(@"File: %@",txtFileContents);
I get "null" as the result. How do I know what path to specify?
thanks
(I placed the file just under "Groups and Files" ... so not sure if I need to specify a path or just the file name. Maybe there is something else wrong ???
Upvotes: 12
Views: 17447
Reputation: 19867
I think the backslash in your path is confusing things. Try this:
NSString *txtFilePath = [[NSBundle mainBundle] pathForResource:@"/help" ofType:@"txt"];
Also, as noted in the comments, you need to use the Build Phase of your project to copy the "help.txt" file.
Upvotes: 13
Reputation: 11598
Here's a common file that I include in a ton of my projects (.h first, followed by .m):
I name this one FileHelpers.h:
#import <UIKit/UIKit.h>
NSString *pathInDocumentDirectory(NSString *fileName);
I name this one (of course) FileHelpers.m:
#include "FileHelpers.h"
NSString *pathInDocumentDirectory(NSString *fileName)
{
// Get list of document directories in sandbox
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// Get one and only one document directory from that list
NSString *documentDirectory = [documentDirectories objectAtIndex:0];
// Append passed in file name to that directory, return it
return [documentDirectory stringByAppendingPathComponent:fileName];
} // pathInDocumentDirectory
As an aside, I have to admit that I didn't come up with this solution myself, but it's been so long that I've used it that I can't remember now where I got it. If anyone knows, please feel free to attribute the appropriate credit!
Upvotes: 2
Reputation: 16024
Try this. What you want is the path to help.txt
but you have to split it up into its name and extension for the method to work.
NSString *txtFilePath = [[NSBundle mainBundle] pathForResource: @"help" ofType: @"txt"];
It also wouldn't hurt to specify NULL
instead of nil
for the error argument. This is because nil
represents objects whereas NULL
represents pointers.
Upvotes: 5