• Re: A good idiom for EOF when READing files?

    From B. Pym@Nobody447095@here-nor-there.org to comp.lang.lisp on Mon Jun 23 13:21:10 2025
    From Newsgroup: comp.lang.lisp

    but then I noticed that if the file had the symbol EOF in it, then the READing would be short-circuited. In particular, if a file "foo" has
    the contents:
    [...]
    After a bit of thought, it occurred to me that I could use a gensym as
    the EOF indicator, as:

    Yep, that's one common way of dealing with it. Personally, I use:

    (defvar *eof* (gensym))

    So at least this way, I only have one gensym per image used on eof
    values. Plus I find it a tiny bit clearer.

    (defun list-expressions (file)
    (with-open-file (instream file :direction :input)
    (let ((eof (gensym))) ;generate a safe EOF marker
    (do ((sexp (read instream nil eof) (read instream nil eof))
    (output nil (push sexp output)))
    ((eql sexp eof) (nreverse output))))))

    (defun list-expressions (file)
    (with-open-file (instream file :direction :input)
    (loop for sexp = (read instream nil *eof*)
    until (eql sexp *eof*)
    collect sexp)))

    Oh yeah, unlike Graham, I like LOOP. Go ahead and use DO until you
    feel comfortable with it, and with Lisp in general, then give LOOP a
    spin.

    Gauche Scheme

    (use srfi-42 :only (list-ec))

    (define (list-expressions file)
    (call-with-input-file file
    (lambda (inport) (list-ec (:port x inport) x))))

    Another way:

    (define (list-expressions file)
    (call-with-input-file file port->sexp-list))
    --- Synchronet 3.21d-Linux NewsLink 1.2