with-open-stream
with-open-stream Macro
Syntax:
with-open-stream (var stream) {declaration}* {form}*
→ {result}*
Arguments and Values:
var—a variable name.
stream—a form; evaluated to produce a stream.
declaration—a declare expression; not evaluated.
forms—an implicit progn.
results—the values returned by the forms.
Description:
with-open-stream performs a series of operations on stream, returns a value, and then closes the stream.
Var is bound to the value of stream, and then forms are executed as an implicit progn. stream is automatically closed on exit from with-open-stream, no matter whether the exit is normal or abnormal. The stream has dynamic extent; its extent ends when the form is exited.
The consequences are undefined if an attempt is made to assign the the variable var with the forms.
Examples:
(with-open-stream (s (make-string-input-stream "1 2 3 4"))
(+ (read s) (read s) (read s))) → 6
Side Effects:
The stream is closed (upon exit).
See Also:
closeExpanded Reference: with-open-stream
Basic Usage
with-open-stream binds a variable to a stream, executes the body, and closes the stream on exit (whether normal or abnormal).
(with-open-stream (s (make-string-input-stream "1 2 3 4"))
(+ (read s) (read s) (read s)))
=> 6
Automatic Cleanup
The stream is closed even if the body exits abnormally.
(let (saved)
(ignore-errors
(with-open-stream (s (make-string-input-stream "test"))
(setq saved s)
(error "bail out")))
(open-stream-p saved))
=> NIL
With Constructed Streams
with-open-stream is useful for composite streams that need cleanup.
(let ((out (make-string-output-stream)))
(with-open-stream (echo (make-echo-stream
(make-string-input-stream "echo-me")
out))
(read echo))
(get-output-stream-string out))
=> "echo-me"
Return Value
Returns the values of the last form in the body.
(with-open-stream (s (make-string-input-stream "hello"))
(values (read-char s) (read-char s)))
=> #\h
=> #\e