GCD读写文件

转: http://blog.sina.com.cn/s/blog_6d01cce30101hzws.html


//GCD读写文件

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    

    int intbuffer[] = { 1, 2, 3, 4 };

    char charbuffer[]={"fdafdsafsdfasdfa"};

    dispatch_data_t data = dispatch_data_create(charbuffer, 4 * sizeof(int), queue, NULL);

    

    dispatch_semaphore_t sem = dispatch_semaphore_create(0);

    // Write

    dispatch_fd_t fd = open("/tmp/data.txt", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU | S_IRWXG | S_IRWXO);

    

    printf("FD: %d\n", fd);

    

    dispatch_write(fd, data, queue,^(dispatch_data_t d, int e) {

        printf("Written %zu bytes!\n", dispatch_data_get_size(data) - (d ? dispatch_data_get_size(d) : 0));

        printf("\tError: %d\n", e);

        dispatch_semaphore_signal(sem);

    });

    

    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);

    

    close(fd);

    

    // Read

    fd = open("/tmp/data.txt", O_RDWR);

    

    dispatch_read(fd, 4 * sizeof(int), queue, ^(dispatch_data_t d, int e) {

        printf("Read %zu bytes!\n", dispatch_data_get_size(d));

        const void *buffer = NULL;

        size_t size = dispatch_data_get_size(d);

        dispatch_data_t tmpData = dispatch_data_create_map(data, &buffer, &size);

        NSData *nsdata = [[NSData alloc] initWithBytes:buffer length:size];

        NSString *s=[[NSString alloc] initWithData:nsdata encoding:NSUTF8StringEncoding];

        NSLog(@"buffer %@",s);

        printf("\tError: %d\n", e);

        dispatch_semaphore_signal(sem);

    });

    

    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);

    close(fd);

    

    // Exit confirmation

    getchar();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值