How to implement the tail command using CL?

"open file" will be read from the beginning of the file. If the file is VERY large, how to read the last 20 lines efficiently?

Respectfully!

+4
source share
1 answer

This opens the file, reads the last byte and closes the file.

(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. 

If you want to specifically read the last lines of n , you will need to read an indefinite number of bytes until you get n+1 new lines. To do this, you will need to either read the blocks back (faster, but spin up while reading unused bytes), or read bytes (slower, but allow for accuracy and a slightly more obvious algorithm).

I suspect tail has a reasonable algorithm used for this, so it is probably worth reading tail

+6
source

Source: https://habr.com/ru/post/1403809/


All Articles