Skip to main content

read-char

read-char Function

Syntax:

read-char &optional input-stream eof-error-p eof-value recursive-p → char

Arguments and Values:

input-stream—an input stream designator . The default is standard input.

eof-error-p—a generalized boolean. The default is true.

eof-value—an object. The default is nil.

recursive-p—a generalized boolean. The default is false.

char—a character or the eof-value.

Description:

read-char returns the next character from input-stream.

When input-stream is an echo stream, the character is echoed on input-stream the first time the character is seen. Characters that are not echoed by read-char are those that were put there by unread-char and hence are assumed to have been echoed already by a previous call to read-char.

If recursive-p is true, this call is expected to be embedded in a higher-level call to read or a similar function used by the Lisp reader .

If an end of file2 occurs and eof-error-p is false, eof-value is returned.

Examples:

(with-input-from-string (is "0123") 
(do ((c (read-char is) (read-char is nil ’the-end)))
((not (characterp c)))
(format t "~S " c)))
▷ #\0 #\1 #\2 #\3
→ NIL

Affected By:

*standard-input*, *terminal-io*.

Exceptional Situations:

If an end of file2 occurs before a character can be read, and eof-error-p is true, an error of type end-of-file is signaled.

See Also:

read-byte, read-sequence, write-char, read

Notes:

The corresponding output function is write-char.

Expanded Reference: read-char

Basic Usage

read-char reads and returns one character from an input stream.

(with-input-from-string (s "abc")
(list (read-char s) (read-char s) (read-char s)))
=> (#\a #\b #\c)

Handling End of File

By default, read-char signals an error at end of file. Pass nil for eof-error-p to return a custom value instead.

(with-input-from-string (s "xy")
(list (read-char s nil :eof)
(read-char s nil :eof)
(read-char s nil :eof)))
=> (#\x #\y :EOF)

Iterating Over Characters

A common pattern is to read characters in a loop until end of file.

(with-input-from-string (s "0123")
(do ((c (read-char s) (read-char s nil 'the-end)))
((not (characterp c)) c)
(format t "~S " c)))
; prints: #\0 #\1 #\2 #\3
=> THE-END

Collecting Characters into a List

(with-input-from-string (s "Hello")
(loop for c = (read-char s nil nil)
while c
collect c))
=> (#\H #\e #\l #\l #\o)