Reading /(Writing) Data from / (to) a Descriptor (Dispatch Sources)

// Read
dispatch_source_t ProcessContentsOfFile(const char* filename)
  {
     // Prepare the file for reading.
     int fd = open(filename, O_RDONLY);
     if (fd == -1)
        return NULL;
     fcntl(fd, F_SETFL, O_NONBLOCK);  // Avoid blocking the read operation
     dispatch_queue_t queue =
  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fd, 0, queue);
     if (!readSource)
     {
close(fd);
        return NULL;
     }
     // Install the event handler
     dispatch_source_set_event_handler(readSource, ^{
        size_t estimated = dispatch_source_get_data(readSource) + 1;
        // Read the data into a text buffer.
        char* buffer = (char*)malloc(estimated);
        if (buffer)
        {
           ssize_t actual = read(fd, buffer, (estimated));
           Boolean done = MyProcessFileData(buffer, actual);  // Process the data.
// Release the buffer when done.
           free(buffer);
           // If there is no more data, cancel the source.
           if (done)
              dispatch_source_cancel(readSource);
        }
});
     // Install the cancellation handler
     dispatch_source_set_cancel_handler(readSource, ^{close(fd);});
     // Start reading the file.
     dispatch_resume(readSource);
     return readSource;
}
</pre><pre name="code" class="objc">
// Write
</pre><pre name="code" class="objc"><pre name="code" class="objc">dispatch_source_t WriteDataToFile(const char* filename)
  {
      int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC,
                        (S_IRUSR | S_IWUSR | S_ISUID | S_ISGID));
      if (fd == -1)
          return NULL;
      fcntl(fd, F_SETFL); // Block during the write.
      dispatch_queue_t queue =
  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
      dispatch_source_t writeSource =
  dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE,
if (!writeSource)
{
close(fd);
    return NULL;
}
fd, 0, queue);
dispatch_source_set_event_handler(writeSource, ^{
    size_t bufferSize = MyGetDataSize();
    void* buffer = malloc(bufferSize);
    size_t actual = MyGetData(buffer, bufferSize);
    write(fd, buffer, actual);
free(buffer);
          // Cancel and release the dispatch source when done.
          dispatch_source_cancel(writeSource);
      });
      dispatch_source_set_cancel_handler(writeSource, ^{close(fd);});
      dispatch_resume(writeSource);
      return (writeSource);
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值