受Apple's documentation的啓發,我正在嘗試使用GCD調度源從文件異步讀取,而不是使用傳統的NSInputStream
和基於運行循環的方法。調度源讀取器 - 如何檢測文件結束?
但是,我不知道如何檢測完成讀取文件。用NSInputStream
,你的代表得到一個NSStreamEventEndEncountered
事件。對於調度源,我認爲事件處理程序將在文件結束時被調用,但似乎並非如此。我錯過了什麼?
這裏是我的代碼:
const char* fileName = "/Users/Nick/Music/iTunes/iTunes Music Library.xml";
int fd = open(fileName, O_NONBLOCK|O_RDONLY);
assert(fd>0);
dispatch_source_t readerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, fd, 0, dispatch_get_main_queue());
dispatch_source_set_event_handler(readerSource, ^{
char buffer[1024];
size_t estimatedLength = dispatch_source_get_data(readerSource);
ssize_t bytesRead = read(fd, buffer, MIN(1024, estimatedLength));
if (bytesRead < 0) {
if (errno != EAGAIN) {
printf("Unexpected error!");
abort();
}
} else if (bytesRead > 0) {
printf("Got %ld bytes of data.\n", bytesRead);
} else {
// bytesRead == 0
printf("EOF encountered!\n");
dispatch_source_cancel(readerSource);
}
});
dispatch_source_set_cancel_handler(readerSource, ^{
printf("Cancel handler was called.\n");
close(fd);
dispatch_release(readerSource);
});
dispatch_resume(readerSource);
謝謝你,我不知道的「普通文件」的區別。 – 2011-05-10 11:18:03