get-output-stream-string
get-output-stream-string Function
Syntax:
get-output-stream-string string-output-stream → string
Arguments and Values:
string-output-stream—a stream.
string—a string.
Description:
Returns a string containing, in order, all the characters that have been output to string-output stream. This operation clears any characters on string-output-stream, so the string contains only those characters which have been output since the last call to get-output-stream-string or since the creation of the string-output-stream, whichever occurred most recently.
Examples:
(setq a-stream (make-string-output-stream)
a-string "abcdefghijklm") → "abcdefghijklm"
(write-string a-string a-stream) → "abcdefghijklm"
(get-output-stream-string a-stream) → "abcdefghijklm"
(get-output-stream-string a-stream) → ""
Side Effects:
The string-output-stream is cleared.
Exceptional Situations:
The consequences are undefined if stream-output-string is closed.
The consequences are undefined if string-output-stream is a stream that was not produced by make-string-output-stream. The consequences are undefined if string-output-stream was created implicitly by with-output-to-string or format.
See Also:
make-string-output-streamExpanded Reference: get-output-stream-string
Basic Usage
get-output-stream-string returns a string containing all characters written to a string output stream created by make-string-output-stream.
(let ((s (make-string-output-stream)))
(write-string "abcdefghijklm" s)
(get-output-stream-string s))
=> "abcdefghijklm"
Clearing Behavior
Each call to get-output-stream-string clears the accumulated characters, so subsequent calls only return what was written after the previous retrieval.
(let ((s (make-string-output-stream)))
(write-string "first" s)
(let ((r1 (get-output-stream-string s)))
(write-string "second" s)
(let ((r2 (get-output-stream-string s)))
(let ((r3 (get-output-stream-string s)))
(list r1 r2 r3)))))
=> ("first" "second" "")
Collecting Formatted Output
Useful for building strings incrementally with various output operations.
(let ((s (make-string-output-stream)))
(princ 42 s)
(write-char #\Space s)
(princ "is the answer" s)
(get-output-stream-string s))
=> "42 is the answer"
Accumulating Output in a Loop
A common pattern is writing to a string stream in a loop, then extracting the result.
(let ((s (make-string-output-stream)))
(dolist (word '("Common" "Lisp" "is" "great"))
(write-string word s)
(write-char #\Space s))
(string-trim " " (get-output-stream-string s)))
=> "Common Lisp is great"