Skip to content

Instantly share code, notes, and snippets.

@asaday
Created March 2, 2013 13:35
Show Gist options
  • Save asaday/5070996 to your computer and use it in GitHub Desktop.
Save asaday/5070996 to your computer and use it in GitHub Desktop.
one of example read line for NSFileHandle
@interface NSFileHandle (fhreadline)
-(NSString*)readLine;
@end
@implementation NSFileHandle (fhreadline)
-(NSString*)readLine
{
unsigned long long pos = [self offsetInFile];
NSMutableData *r = [NSMutableData data];
const char *buf = NULL;
int p = 0;
char ch = 0;
for(int rlen = 32 ; rlen ; rlen *= 2)
{
NSData *d = [self readDataOfLength:rlen];
if(!d) return nil;
int dlen = d.length;
if(!p && !dlen) return nil;
[r appendData:d];
if(dlen < rlen) [r appendBytes:"\r\n" length:2];
buf = r.bytes;
for(; p < r.length-1 ; p++)
{
ch = buf[p];
if(ch == 0x0d || ch == 0x0a)
{
rlen = 0;
break;
}
}
}
NSString *rs = [[NSString alloc] initWithData:[r subdataWithRange:NSMakeRange(0, p)] encoding:NSUTF8StringEncoding];
p++;
if(ch == 0x0d && buf && buf[p] == 0x0a) p++; // LF skip (for CR+LF)
[self seekToFileOffset:pos+p]; // dont worry overseek
return rs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment