7

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

apaderno
  • 26,733
  • 16
  • 74
  • 87
satish
  • 1,235
  • 3
  • 14
  • 14

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,067
  • 23
  • 80
  • 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
  • 100,816
  • 18
  • 175
  • 263
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
  • 11,631
  • 7
  • 40
  • 63