Skip to content

Instantly share code, notes, and snippets.

@mdippery
Created January 12, 2011 23:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdippery/777080 to your computer and use it in GitHub Desktop.
Save mdippery/777080 to your computer and use it in GitHub Desktop.
A class that mimics `tail -f`
//
// 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