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();

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页