Objective-C stream file lines with NSInputStream
Objective-C
#import <Foundation/Foundation.h>
static void ReadLines(NSString *path, void (^onLine)(NSString *)) {
NSInputStream *in = [NSInputStream inputStreamWithFileAtPath:path];
[in open];
uint8_t buf[4096];
NSMutableData *pending = [NSMutableData data];
NSData *nl = [NSData dataWithBytes:(uint8_t[]){10} length:1];
NSInteger n = 0;
while ((n = [in read:buf maxLength:sizeof buf]) > 0) {
[pending appendBytes:buf length:(NSUInteger)n];
NSRange r;
while ((r = [pending rangeOfData:nl options:0 range:NSMakeRange(0, pending.length)]).location != NSNotFound) {
NSString *line = [[NSString alloc] initWithData:[pending subdataWithRange:NSMakeRange(0, r.location)] encoding:NSUTF8StringEncoding];
if (line) onLine(line);
[pending replaceBytesInRange:NSMakeRange(0, r.location + r.length) withBytes:NULL length:0];
}
}
[in close];
if (pending.length > 0) onLine([[NSString alloc] initWithData:pending encoding:NSUTF8StringEncoding] ?: @"");
}