如何在便携式 C 中从管道读取时向前查找
由于 fseek()
不适用于管道,有什么方法可以模拟向前搜索?简单的方法是使用 fread() 并丢弃读入内存缓冲区的内容。为了避免巨大的缓冲区,您可以一遍又一遍地使用相同的缓冲区,并仅使用缓冲区的一部分进行最终读取。
但这是唯一的方法吗?是否有另一种方法可以避免缓冲区和潜在的多次读取?
Since fseek()
does not work on pipes what methods exist for simulating seeking forward? The naive approach is to use fread()
and throw away the contents read into the memory buffer. For huge seeks to avoid huge buffers you would use the same buffer over and over with the final read using just a part of the buffer.
But is this the only approach? Is there another way which avoids the buffer and the potential multiple read?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查找在管道上没有意义,因为输入是动态生成的(不存储在磁盘上)。没有为管道实现
lseek
内核系统调用。还要记住,管道本质上是一个有限、固定大小的生产者-消费者缓冲区。当它满了时,生产者会被挂起,直到消费者读取到最旧的数据。
Seeking doesn't make sense on pipes because the input is produced dynamically (not stored on disk). The
lseek
kernel system call is not implemented for pipes.Also have in mind that a pipe is essentially a producer-consumer buffer of a limited, fixed size. When it gets full, the producer is suspended until the consumer reads the oldest data.
是的,这是唯一的方法。我会使用 1k-8k 左右的缓冲区。如果较小,则读取的系统调用开销将发挥作用,如果较大,您将从缓存中逐出有用的数据。
Yes, it is the only way. I would use a buffer somewhere around 1k-8k. With much smaller the syscall overhead for read will come into play, and with much larger you'll evict useful data from the cache.