Why is a read line executed twice to read from a file in Lisp?

This is the code for implementing the "cat" command with lisp, as described in ANSI Common Lisp , page 122.

  (defun pseudo-cat (file)
   (with-open-file (str file: direction: input)
     (do ((line (read-line str nil 'eof)
                (read-line str nil 'eof)))
         ((eql line 'eof))
       (format t "~ A ~%" line))))

Why is the read-line function executed twice? I tried to run it with only one line of reading, but Lisp could not finish the code.

+6
input lisp common-lisp
source share
3 answers

Syntax of DO variables: variable, initialization form, update form. In this case, the initialization form coincides with the update form. But there is no transcript in DO for this case, so you need to record it twice.

+11
source share

You need to read the DO syntax: http://www.lispworks.com/documentation/HyperSpec/Body/m_do_do.htm

The first READ-LINE form is an init form, and the second is a power form. Therefore, in the first iteration, the variable is set to the result of the init form. In the following iterations, the variable is assigned the value of the step form.

+5
source share

You can use (listen file) for the test if you can read from the file.

This is my print-file function

 (defun print-file (filename) "Print file on stdout." (with-open-file (file filename :direction :input) (loop (when (not (listen file)) (return)) (write-line (read-line file))))) 
0
source share

All Articles