阅读文件
可以使用 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。