Newsgroups: comp.lang.lisp
Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!think.com!mintaka!mintaka!pld
From: pld@whopper.lcs.mit.edu (Peter L. DeWolf)
Subject: Re: multiple use of with-open-file, or with-open-stream
In-Reply-To: vinson@linc.cis.upenn.edu's message of 24 Jun 91 14:16:42 GMT
Message-ID: <PLD.91Jun24130012@whopper.lcs.mit.edu>
Sender: news@mintaka.lcs.mit.edu
Reply-To: pld@mcrc.mot.com
Organization: MIT Lab for Computer Science, Cambridge, Mass.
References: <45084@netnews.upenn.edu>
Date: 24 Jun 91 13:00:12
Lines: 30

> Is there some way (a macro?) that I can get the functionality of
> with-open-file and with-open-stream without initially knowing how many
> files (or stream) I will have initially?  My current solution is to
> open all the files, run the body of the program, and then close
> everything.  This is fine, until my program bombs (and it's kinda
> large) and I have to remember to close out all the streams by hand.

The primitive used by (with-open-file) to close things in the face of
errors is (unwind-protect).  That's easy enough to use.  Here's a
trivial function that opens an arbitrary number of files and causes an
error.  It automatically closes the files even if you abort out of the
error.

(defun open-many-files (&rest files)
  (let ((streams nil))
    (unwind-protect
      (progn
        (dolist (file files)
          (push (open file) streams))
        (error "Too bad"))
     ;;Here's the cleanup form.  Close all the files...
     (dolist (stream streams)
       (close stream)))))

 - Peter
--

   Peter L. DeWolf
   Motorola Cambridge Research Center
   pld@mcrc.mot.com -or- pld@abp.lcs.mit.edu
