ファイル内の特定の行を読み込む - lisp-cookbook-ja/common-lisp GitHub Wiki
ファイル内の特定の行を読み込む
標準にファイルの読み込みで行を指定する方法ははありませんので、ライブラリを利用するか、自作することになるでしょう。
CLiki:Series を利用した例
(in-package :series)
(defun read-nth-line (pos file)
(collect-nth pos
(scan-file file #'read-line)))
;; 実行例
(read-nth-line 666 "/usr/share/dict/words")
;=> "Andrianampoinimerina's"
file-positionを利用した例
(defun read-nth-line (pos file)
(with-open-file (in file)
(let ((pos (nth-beginning-of-line-position pos file)))
(when pos
(file-position in pos)
(read-line in)))))
(defun nth-beginning-of-line-position (n file &optional (newline-char #\Newline))
(with-open-file (in file)
(loop :with newline := newline-char
:for char := (read-char in nil nil) :while char
:when (eql newline char) :count :it :into cnt
:when (>= cnt n) :return (file-position in)
:finally (return NIL))))