Created
March 2, 2013 13:35
-
-
Save asaday/5070996 to your computer and use it in GitHub Desktop.
one of example read line for NSFileHandle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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