1

What is the easiest and most terse way to read a file line-by-line in Objective-C?

If you think using the methods from C/C++ are better, please let me know.

Thanks!

Shyamal Chandra
  • 129
  • 3
  • 12

2 Answers2

5

If you have small files you can do the following:

NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
for (NSString *line in [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {
    // Do something
}

otherwise, see this question for a more robust solution.

Community
  • 1
  • 1
Attila H
  • 3,616
  • 2
  • 24
  • 37
0

Well, in two lines:

NSString *s = [NSString stringWithContentsOfFile:@"foo.txt" encoding:NSUTF8StringEncoding error:NULL];
NSArray lines = [s componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];