read single line from text file in objective-C

狂风中的少年 提交于 2019-12-12 19:18:53

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/1878815/read-single-line-from-text-file-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!