"with-open- file“将从文件的开头开始读取。如果文件非常大,如何有效地读取最后20行?
真心的!
发布于 2012-03-29 00:28:19
这将打开一个文件,读取最后一个字节,然后关闭该文件。
(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来获得指导。
https://stackoverflow.com/questions/9901700
复制相似问题