“with-open-file”将从文件的开头读取。如果文件非常大,如何有效地读取最后 20 行?
真挚地!
最佳答案
这将打开一个文件,读取最后一个字节,然后关闭文件。
(defun read-final-byte (filename)
(with-open-file (s filename
:direction :input
:if-does-not-exist :error)
(let ((len (file-length s)))
(file-position s (1- len)) ; 0-based position.
(read-char s nil)))) ; don't error if reading the end of the file.
如果想具体看最后
n
行,你将不得不读回不确定数量的字节,直到你得到 n+1
换行符。为了做到这一点,您将不得不向后进行块读取(更快但最终会读取不需要的字节),或字节读取(较慢但允许精度和稍微更明显的算法)。我怀疑
tail
对此应用了合理的算法,因此它可能值得一读 tail
的 source为指导方针。
关于common-lisp - 如何使用 CL 实现 `tail` 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9901700/