Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading text file with NSString:stringWithContentsOfFile?

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 ???

like image 988
Kristen Martinson Avatar asked Jul 13 '11 01:07

Kristen Martinson


3 Answers

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.

like image 188
highlycaffeinated Avatar answered Nov 01 '22 22:11

highlycaffeinated


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.

like image 39
Alexsander Akers Avatar answered Nov 01 '22 22:11

Alexsander Akers


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!

like image 2
mbm29414 Avatar answered Nov 01 '22 22:11

mbm29414