PDA

View Full Version : Reading from a file in Obj-C




MacFan26
Nov 4, 2007, 02:08 PM
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:@"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!



Catfish_Man
Nov 4, 2007, 03:42 PM
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:@"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.

MacFan26
Nov 5, 2007, 11:39 PM
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:@"one.jpg"];

GeeYouEye
Nov 6, 2007, 01:02 AM
*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.

Catfish_Man
Nov 6, 2007, 02:20 AM
Indeed. NSBundle is your best friend for easy access to resources :)

MacFan26
Nov 12, 2007, 06:39 PM
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:@"../../data.txt"];


Sorry for the newbiness, I'm just asking..

HiRez
Nov 12, 2007, 07:34 PM
Just use mainBundle: and pathToResource: and it'll take care of finding it for you.

NSString *fileContents = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathToResource:"data" ofType:"txt"]];