suse
suse

Reputation: 10563

read single line from text file in objective-C

i'm new to iPhone programming and coding in XCode SDK.I want to access and read the configuration file which i have placed in Resource folder in XCode,my configuration file looks like this

@key=value$
@vinu=flower$
@cathy=fruit$

I want to compare the key and access the value from configuration file. Since i'm working with iPhone OS, i cant use NSWorkspace.Hence i'm using NSFileHandle. This is how my code looks like,

NSString *path = [[NSBundle mainBundle] pathForResource:@"configuration" ofType:@"txt"];
NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:path];

NSString *txtString = [[NSString alloc] initWithData: 
                                  [readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding];

please let me know is the procedure correct, and how to proceed. ??

Thank You.

Upvotes: 2

Views: 3740

Answers (1)

Dave DeLong
Dave DeLong

Reputation: 243146

Do yourself a favor and save it as a plist, and not a straight text file.

However, if you need to read it in like that, the simplest way is to read it into a string and then go from there, ie:

NSString * fileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

If the file is super large and the only reasonable way to read it is line-by-line, then you can quickly see that this is something that has come up before (Particularly: Objective-C: Reading a file line by line).

Upvotes: 2

Related Questions