Next: , Up: Input and Output

5.12.1 Ports

Sequential input/output in Scheme is represented by operations on a port. This chapter explains the operations that Guile provides for working with ports.

Ports are created by opening, for instance open-file for a file (see File Ports). Characters can be read from an input port and written to an output port, or both on an input/output port. A port can be closed (see Closing) when no longer required, after which any attempt to read or write is an error.

The formal definition of a port is very generic: an input port is simply “an object which can deliver characters on demand,” and an output port is “an object which can accept characters.” Because this definition is so loose, it is easy to write functions that simulate ports in software. Soft ports and string ports are two interesting and powerful examples of this technique. (see Soft Ports, and String Ports.)

Ports are garbage collected in the usual way (see Memory Management), and will be closed at that time if not already closed. In this case any errors occuring in the close will not be reported. Usually a program will want to explicitly close so as to be sure all its operations have been successful. Of course if a program has abandoned something due to an error or other condition then closing problems are probably not of interest.

It is strongly recommended that file ports be closed explicitly when no longer required. Most systems have limits on how many files can be open, both on a per-process and a system-wide basis. A program that uses many files should take care not to hit those limits. The same applies to similar system resources such as pipes and sockets.

Note that automatic garbage collection is triggered only by memory consumption, not by file or other resource usage, so a program cannot rely on that to keep it away from system limits. An explicit call to gc can of course be relied on to pick up unreferenced ports. If program flow makes it hard to be certain when to close then this may be an acceptable way to control resource usage.

All file access uses the “LFS” large file support functions when available, so files bigger than 2 Gbytes (2^31 bytes) can be read and written on a 32-bit system.

— Scheme Procedure: input-port? x
— C Function: scm_input_port_p (x)

Return #t if x is an input port, otherwise return #f. Any object satisfying this predicate also satisfies port?.

— Scheme Procedure: output-port? x
— C Function: scm_output_port_p (x)

Return #t if x is an output port, otherwise return #f. Any object satisfying this predicate also satisfies port?.

— Scheme Procedure: port? x
— C Function: scm_port_p (x)

Return a boolean indicating whether x is a port. Equivalent to (or (input-port? x) (output-port? x)).