閱讀檔案
可以使用 WITH-OPEN-FILE
巨集開啟檔案以作為流進行讀取 。
(with-open-file (file #P"test.file")
(loop for i from 0
for line = (read-line file nil nil)
while line
do (format t "~d: ~a~%" i line)))
; 0: Foobar
; 1: Barfoo
; 2: Quuxbar
; 3: Barquux
; 4: Quuxfoo
; 5: Fooquux
;=> T
(let ((file (open #P"test.file"))
(aborted t))
(unwind-protect
(progn
(loop for i from 0
for line = (read-line file nil nil)
while line
do (format t "~d: ~a~%" i line))
(setf aborted nil))
(close file :abort aborted)))
請注意,READ-LINE
為每一行建立一個新字串。這可能很慢。一些實現提供了一種變體,它可以將一行讀入字串緩衝區。示例: Tihuan5 for Allegro CL。