User Tools



  • with-open-file (stream filespec options*) declaration* form*results

Arguments and Values

stream -- a variable. filespec - a pathname designator. options -- forms; evaluated. declaration - a declare expression; not evaluated. forms - an implicit progn. results - the values returned by the forms.


with-open-file uses open to create a file stream to file named by filespec.

filespec is the name of the file to be opened. options are used as keyword arguments to open.

The stream object to which the stream variable is bound has dynamic extent; its extent ends when the form is exited.

with-open-file evaluates the forms as an implicit progn with stream bound to the value returned by open.

When control leaves the body, either normally or abnormally (such as by use of throw), the file is automatically closed. If a new output file is being written, and control leaves abnormally, the file is aborted and the file system is left, so far as possible, as if the file had never been opened.

It is possible by the use of :if-exists nil or :if-does-not-exist nil for stream to be bound to nil.

Users of :if-does-not-exist nil should check for a valid stream.

The consequences are undefined if an attempt is made to assign the stream variable. The compiler may choose to issue a warning if such an attempt is detected.


(setf *p* (merge-pathnames "test"))


(with-open-file (s *p* :direction :output :if-exists :supersede) (format s "Here are a couple~%of test data lines~%"))


(with-open-file (s *p*) (do ((l (read-line s) (read-line s nil 'eof))) ((eq l 'eof) "Reached end of file.") (format t "~&* ~A~%" l))) <o>* Here are a couple * of test data lines</o> <r>"Reached end of file."</r> </blockquote> Normally one would not do this intentionally because it is not perspicuous, but beware when using :if-does-not-exist nil that this doesn't happen to you accidentally... <blockquote> (with-open-file (foo "no-such-file" :if-does-not-exist nil) (read foo)) <o>hello?</o> <r>HELLO? ; This value was read from the terminal, not a file!</r> </blockquote> Here's another bug to avoid... <blockquote> (with-open-file (foo "no-such-file" :direction :output :if-does-not-exist nil) (format foo "Hello")) <r>"Hello" ; FORMAT got an argument of NIL!</r> </blockquote> ====Side Effects==== Creates a stream to the file named by filename (upon entry), and closes the stream (upon exit). In some implementations, the file might be locked in some way while it is open. If the stream is an output stream, a file might be created. ====Affected By==== The host computer's file system. ====Exceptional Situations==== See the function open. ====See Also==== * Function OPEN * Function CLOSE * System Class PATHNAME * System Class LOGICAL-PATHNAME**

  • {\secref\PathnamesAsFilenames}

====Notes==== None.