Prev Up Next

Scheme's I/O procedures do not need a port argument if the port happens to be standard input or standard output. However, if you need these ports explicitly, the zero-argument procedures current-input-port and current-output-port furnish them. Thus,

(display 9)
(display 9 (current-output-port))

have the same behavior.

A port is associated with a file by opening the file. The procedure open-input-file takes a filename argument and returns a new input port associated with it. The procedure open-output-file takes a filename argument and returns a new output port associated with it. It is an error to open an input file that doesn't exist, or to open an output file that already exists.

After you have performed I/O on a port, you should close it with close-input-port or close-output-port.

In the following, assume the file hello.txt contains the single word hello.

(define i (open-input-file "hello.txt"))

(read-char i)
=> #\h

(define j (read i))

j
=> ello

Assume the file greeting.txt does not exist before the following programs are fed to the listener:

(define o (open-output-file "greeting.txt"))

(display "hello" o)
(write-char #\space o)
(display 'world o)
(newline o)

(close-output-port o)

The file greeting.txt will now contain the line:

hello world

7.3.1  Automatic opening and closing of file ports

Scheme supplies the procedures call-with-input-file and call-with-output-file that will take care of opening a port and closing it after you're done with it.

The procedure call-with-input-file takes a filename argument and a procedure. The procedure is applied to an input port opened on the file. When the procedure completes, its result is returned after ensuring that the port is closed.

(call-with-input-file "hello.txt"
  (lambda (i)
    (let* ((a (read-char i))
           (b (read-char i))
           (c (read-char i)))
      (list a b c))))
=> (#\h #\e #\l)

The procedure call-with-output-file does the analogous services for an output file.

Prev Up Next