A file can be opened for reading as a stream using WITH-OPEN-FILE
macro.
(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
The same can be done manually using OPEN
and CLOSE
.
(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)))
Note that READ-LINE
creates a new string for each line. This can be slow. Some implementations provide a variant, which can read a line into a string buffer. Example: READ-LINE-INTO
for Allegro CL.