gpt4 book ai didi

c - 调度源阅读器 - 如何检测文件结尾?

转载 作者:行者123 更新时间:2023-12-03 16:20:44 26 4
gpt4 key购买 nike

灵感来自Apple's documentation ,我正在尝试使用 GCD 调度源从文件中异步读取,而不是使用传统的 NSInputStream 和基于运行循环的方法。

但是,我不确定如何检测何时读完文件。使用 NSInputStream,您的委托(delegate)会收到一个 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);

最佳答案

据我所知,您必须将读取的字节与文件的长度进行比较。

此外,GCD 调度源使用带有 EVFILT_READ 的 kqueue,因此对于常规文件来说并不是很有用。我建议您使用打开/lseek/读取/关闭全局队列中的文件。

  • Re: kqueue and EVFILT_READ on files

    For the most part, read filters are not really useful for regular files, since - well - they are always readable, so long as they have data remaining in them, and they will give a clear EOF condition. You can't really treat files as if they were pipes - i.e. don't expect a fle whose fp is at EOF that then gets extended so there is more data in the file to result in an EVFILT_READ coming true. This will work in the non-EV_POLL case, for regular files, but it's not going to work for special files.

    Likewise, at least for most normal block devices (disks, etc.), the are also always readable until you hit the end of the device, and there's a clear EOF indication there, too, so they are not too useful there, either (it's not like more disk blocks will suddenly be arriving on a platter that was built in 1998, for example).

关于c - 调度源阅读器 - 如何检测文件结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5621002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com