DISPATCH_SOURCE_TYPE_READ


#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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容