Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

MacFan26

macrumors 65816
Original poster
Jan 8, 2003
1,219
1
San Francisco, California
Anyone know the best way to read text from a simple .txt file and store it in an NSString? I'm trying to do it like this:

NSString *data = [[NSString alloc] initWithContentsOfFile:mad:"data.txt"];

The data.txt file is in the same source folder as this code. I want to do something similar to reading from a file using Java's Scanner. Thanks for any help!
 
Anyone know the best way to read text from a simple .txt file and store it in an NSString? I'm trying to do it like this:

NSString *data = [[NSString alloc] initWithContentsOfFile:mad:"data.txt"];

The data.txt file is in the same source folder as this code. I want to do something similar to reading from a file using Java's Scanner. Thanks for any help!

You need to use the correct path. Putting it in the same folder as the source won't make it end up in the application at all.
 
You need to use the correct path. Putting it in the same folder as the source won't make it end up in the application at all.

So, for a correct path, do I need something more than "./data.txt" ?

I'm using this to create my images, and it works just fine because they are in my resources folder for the project.

one = [NSImage imageNamed:mad:"one.jpg"];
 
*grumble*

Your current working directory varies with build style, settings, read/write, and phase of the moon. Provide an "Open..." dialog, or else use a semi-hardcoded path (using NSHomeDirectory() if necessary).

EDIT: oh, they're in your Resources folder? Read up on NSBundle.
 
EDIT: oh, they're in your Resources folder? Read up on NSBundle.

Yeah this was for a very simple program where I just wanted to read input from one file. Thanks for letting me know about NSBundle. For now, I guess in XCode if you store something in the resources folder you need to go up two directories from your source to access it, this works fine for me:

NSString *data = [[NSString alloc] initWithContentsOfFile:mad:"../../data.txt"];


Sorry for the newbiness, I'm just asking..
 
Just use mainBundle: and pathToResource: and it'll take care of finding it for you.

Code:
NSString *fileContents = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathToResource:"data" ofType:"txt"]];
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.