Created
January 12, 2011 23:02
-
-
Save mdippery/777080 to your computer and use it in GitHub Desktop.
A class that mimics `tail -f`
This file contains hidden or 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
// | |
// Created by Michael Dippery on 1/12/2011. | |
// Copyright 2011 Michael Dippery. All rights reserved. | |
// | |
#import "FileTailer.h" | |
@implementation FileTailer | |
- (id)initWithPath:(NSString *)path refreshPeriod:(NSTimeInterval)aRefresh | |
{ | |
FILE *fh = fopen([path UTF8String], "r"); | |
if (!fh) { | |
NSLog(@"Could not open file: %@", path); | |
[self autorelease]; | |
return nil; | |
} | |
return [self initWithStream:fh refreshPeriod:aRefresh]; | |
} | |
- (id)initWithStream:(FILE *)fh refreshPeriod:(NSTimeInterval)aRefresh | |
{ | |
if ((self = [super init])) { | |
in = fh; | |
refresh = aRefresh; | |
} | |
return self; | |
} | |
- (void)dealloc | |
{ | |
fclose(in); | |
[super dealloc]; | |
} | |
- (void)readIndefinitely:(void (^)(int ch))action | |
{ | |
long pos = 0L; | |
int ch = 0; | |
while (1) { | |
fseek(in, pos, SEEK_SET); | |
int ch = fgetc(in); | |
pos = ftell(in); | |
if (ch != EOF) { | |
action(ch); | |
} else { | |
[NSThread sleepForTimeInterval:refresh]; | |
} | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment