common-lisp - 如何使用 CL 实现 `tail` 命令?

标签 common-lisp

“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对此应用了合理的算法,因此它可能值得一读 tailsource为指导方针。

关于common-lisp - 如何使用 CL 实现 `tail` 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9901700/

相关文章:

functional-programming - 不使用中间列表过滤范围

lisp - 如果字符串是向量,为什么它们是不可变的?

list - Common Lisp 相当于 Haskell 的副本?

Lisp 重新定义函数

performance - 提高字符串操作的速度

lisp - 通用 Lisp : getting an error using readtable-case

vim - 使用 Vim 进行 Lisp 开发

common-lisp - defmethod 和 defun 的 Common Lisp 特殊变量范围不同?

python - 是什么让(开放的)Dylan 不同于其他编程语言?

multidimensional-array - 在 Common Lisp 中实现多维关联数组