13.1.6 String Ports (original) (raw)

13.1.6 String Ports🔗

A string port reads or writes from a byte string. An input string port can be created from either a byte stringor a string; in the latter case, the string is effectively converted to a byte string using string->bytes/utf-8. An output string port collects output into a byte string, butget-output-string conveniently converts the accumulated bytes to a string.

Input and output string ports do not need to be explicitly closed. The file-position procedure works for string ports in position-setting mode.

+Byte Strings also provides information on bytestrings.

Returns #t if p is a string port, #fotherwise.

Added in version 6.0.1.6 of package base.

Creates an input string port that reads characters frombstr (see Byte Strings). Modifying bstrafterward does not affect the byte stream produced by the port. The optional name argument is used as the name for the returned port.

Examples:

> (define sp (open-input-bytes #"(apples 42 day)"))
> (define sexp1 (read sp))
> (first sexp1)
'apples
> (rest sexp1)
'(42 day)
> (read-line (open-input-bytes #"the cow jumped over the moon\nthe little dog\n"))
"the cow jumped over the moon"

+Strings also provides information on strings.

Creates an input string port that reads bytes from the UTF-8 encoding (see Encodings and Locales) of str. The optionalname argument is used as the name for the returned port.

Examples:

Creates an output string port that accumulates the output into a byte string. The optional name argument is used as the name for the returned port.

Examples:

The same as open-output-bytes.

Examples:

Returns the bytes accumulated in the string port out so far in a freshly allocated byte string (including any bytes written after the port’s current position, if any). The outport must be an output string port produced byopen-output-bytes (or open-output-string) or a structure whose prop:output-port property refers to such an output port (transitively).

If reset? is true, then all bytes are removed from the port, and the port’s position is reset to 0; if reset? is#f, then all bytes remain in the port for further accumulation (so they are returned for later calls toget-output-bytes or get-output-string), and the port’s position is unchanged.

The start-pos and end-pos arguments specify the range of bytes in the port to return; supplying start-pos andend-pos is the same as using subbytes on the result of get-output-bytes, but supplying them toget-output-bytes can avoid an allocation. Theend-pos argument can be #f, which corresponds to not passing a second argument to subbytes.

Examples:

> (define op (open-output-bytes))
> (write '((1 2 3) ("Tom" "Dick") ('a 'b 'c)) op)
> (get-output-bytes op)
#"((1 2 3) (\"Tom\" \"Dick\") ((quote a) (quote b) (quote c)))"
> (get-output-bytes op #f 3 16)
#" 2 3) (\"Tom\" "
> (get-output-bytes op #t)
#"((1 2 3) (\"Tom\" \"Dick\") ((quote a) (quote b) (quote c)))"
> (get-output-bytes op)
#""

Examples: