8.2 Default Ports

For most simple I/O functions, the target port is an optional argument, and the default is the current input port or current output port. Furthermore, error messages are written to the current error port, which is an output port. The current-input-port, current-output-port, and current-error-port functions return the corresponding current ports.

Examples:

  > (display "Hi")

  Hi

  > (display "Hi" (current-output-port)) ; the same

  Hi

If you start the racket program in a terminal, then the current input, output, and error ports are all connected to the terminal. More generally, they are connected to the OS-level stdin, stdout, and stderr. In this guide, the examples show output written to stdout in purple, and output written to stderr in red italics.

Examples:

  (define (swing-hammer)
    (display "Ouch!" (current-error-port)))
  > (swing-hammer)

  Ouch!

The current-port functions are actually parameters, which means that their values can be set with parameterize.

See Dynamic Binding: parameterize for an introduction to parameters.

Example:

  > (let ([s (open-output-string)])
      (parameterize ([current-error-port s])
        (swing-hammer)
        (swing-hammer)
        (swing-hammer))
      (get-output-string s))

  "Ouch!Ouch!Ouch!"