#import "ViewController.h"
@interface ViewController ()
{
dispatch_source_t _readSource;
}
@end
@implementation ViewController
-(BOOL)myProcesFileData:(char *)buffer actutalSize:(size_t)actutalSize fd:(int)fd
{
NSString *str = [[NSString alloc] initWithBytes:buffer length:actutalSize encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
NSLog(@"%li", actutalSize);
if(actutalSize < 260)
{
return YES;
}
else
{
return NO;
}
}
void cancelHandler(void *context)
{
int fd = (int)dispatch_source_get_handle((__bridge dispatch_source_t _Nonnull)(context));
close(fd);
}
-(dispatch_source_t)createFileDispatchSource:(const char *)fileName
{
//1:打开文件,获取文件描述符(open成功则返回文件描述符,否则返回-1)
int fd = open(fileName, O_RDWR);
if (fd == -1)
{
return NULL;
}
//2:设置文件操作为非堵塞模式(也可以在pen函数中设置:open(fileName, O_RDONLY|O_NONBLOCK))
fcntl(fd, F_SETFL, O_NONBLOCK);
//3:创建派发源
dispatch_queue_t queue = dispatch_queue_create("同一文件操作都在串行队列中", DISPATCH_QUEUE_SERIAL);
_readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fd, 0, queue);
if (_readSource == NULL)
{
close(fd);
return NULL;
}
//4:设置”文件可读“事件响应处理器
dispatch_source_set_event_handler(_readSource, ^{
size_t estimated = 260;
char *buffer = (char*)malloc(estimated);
if(buffer)
{
size_t actualSize = read(fd, buffer, estimated);
BOOL done = [self myProcesFileData:buffer actutalSize:actualSize fd:fd];
free(buffer);
if (done)
{
dispatch_source_cancel(_readSource);
}
}
});
//使用函数处理器
dispatch_set_context(_readSource, (__bridge void *)_readSource);
dispatch_source_set_cancel_handler_f(_readSource, cancelHandler);
//6:启动事件源
dispatch_resume(_readSource);
return _readSource;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self createFileDispatchSource:"/Users/weiyanwu/Desktop/ZORead.txt"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
DISPATCH_SOURCE_TYPE_READ
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- http://www.jianshu.com/p/a4ea43179870 http://www.cnblogs....
- 计算机的学习方法本质,就是read the fucking source codehttp://i.mtime.c...
- 光棍节问世没多久就被活脱脱地过成了情人节,大波情侣秀恩爱的浪潮此起彼伏,光棍们内心愤愤不平,连给一个我们的节日都不...