I need to parse a text file, one line at a time. Also, is there EOF in Objective-C?
Asked
Active
Viewed 9,133 times
7
-
1This is a possible duplicate of this question: http://stackoverflow.com/questions/1044334/objective-c-reading-a-file-line-by-line – Brad Larson Aug 24 '09 at 12:17
-
See ParseKit [http://parsekit.com/](http://parsekit.com/) – Robert French Aug 24 '09 at 04:59
3 Answers
17
Something like this might work for you:
NSString *fileContents = [NSString stringWithContentsOfFile:@"myfile.txt"];
NSArray *lines = [fileContents componentsSeparatedByString:@"\n"];
This will give you an array where each element is a line of the string.

rein
- 32,967
- 23
- 82
- 106
-
3And now something like: NSString *fileContents = [NSString stringWithContentsOfFile:@"myFile.txt" encoding:NSUTF8StringEncoding error:nil]; – htafoya Oct 14 '11 at 16:04
2
Objective-C is a proper extension of C. Any C program is a valid Objective-C program. Among other things, this means that EOF defined in the standard C header "stdio.h" is an EOF marker in Objective-C as well.

Stephen Canon
- 103,815
- 19
- 183
- 269
2
stringWithContentsOfFile is deprecated.
Here is an updated answer:
NSError* error;
NSString *fileContent = [NSString stringWithContentsOfFile:txtFilePath encoding:NSUTF8StringEncoding error:&error];
NSArray *lines = [fileContent componentsSeparatedByString:@"\n"];

Aviram Netanel
- 12,633
- 9
- 45
- 69