7

I need to parse a text file, one line at a time. Also, is there EOF in Objective-C?

apaderno
  • 28,547
  • 16
  • 75
  • 90
satish
  • 1,245
  • 3
  • 14
  • 15

3 Answers3

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
  • 3
    And 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