Input and Output
****************

Ports
=====

[Concept of the port abstraction.]

Sequential input/output in Scheme is represented by operations on a port.  Characters can be read from an input port and written to an output port.  This chapter explains the operations that Guile provides for working with ports.

The formal definition of a port is very generic: an input port is simply ``an object which can deliver characters on command,'' 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.

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

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

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

Reading
=======

[Generic procedures for reading from ports.]

 -- primitive: eof-object? x
     Return #t if X is an end-of-file object; otherwise return #f.

 -- primitive: char-ready? [port]
     Return #t if a character is ready on input PORT and return #f otherwise.  If char-ready? returns #t then the next read-char operation on PORT is guaranteed not to hang.  If PORT is a file port at end of file then char-ready? returns #t. (char-ready? exists to make it possible for a program to accept characters from interactive ports without getting stuck waiting for input.  Any input editors associated with such ports must make sure that characters whose existence has been asserted by char-ready? cannot be rubbed out. If char-ready? were to return #f at end of file, a port at end of file would be indistinguishable from an interactive port that has no ready characters.)

 -- primitive: read-char [port]
     Return the next character available from PORT, updating PORT to point to the following character.  If no more characters are available, the end-of-file object is returned.

 -- primitive: peek-char [port]
     Return the next character available from PORT, without updating PORT to point to the following character.  If no more characters are available, the end-of-file object is returned. (The value returned by a call to peek-char is the same as the value that would have been returned by a call to read-char on the same port.  The only difference is that the very next call to read-char or peek-char on that PORT will return the value returned by the preceding call to peek-char.  In particular, a call to peek-char on an interactive port will hang waiting for input whenever a call to read-char would have hung.)

 -- primitive: unread-char cobj port
     Place CHAR in PORT so that it will be read by the next read operation.  If called multiple times, the unread characters will be read again in last-in first-out order.  If PORT is not supplied, the current input port is used.

 -- primitive: unread-string str port
     Place the string STR in PORT so that its characters will be read in subsequent read operations.  If called multiple times, the unread characters will be read again in last-in first-out order.  If PORT is not supplied, the current-input-port is used.

 -- primitive: drain-input port
     Drain PORT's read buffers (including any pushed-back characters) and return the content as a single string.

 -- primitive: port-column port
 -- primitive: port-line port
     Return the current column number or line number of PORT, using the current input port if none is specified.  If the number is unknown, the result is #f.  Otherwise, the result is a 0-origin integer - i.e. the first character of the first line is line 0, column 0. (However, when you display a file position, for example in an error message, we recommend you add 1 to get 1-origin integers.  This is because lines and column numbers traditionally start with 1, and that is what non-programmers will find most natural.)

 -- primitive: set-port-column! port column
 -- primitive: set-port-line! port line
     Set the current column or line number of PORT, using the current input port if none is specified.

 -- primitive: read-string!/partial str [port_or_fdes [start [end]]]
     Read characters from an fport or file descriptor into a string STR.  This procedure is scsh-compatible and can efficiently read large strings.  It will:

       * attempt to fill the entire string, unless the START and/or END arguments are supplied.  i.e., START defaults to 0 and END defaults to (string-length str)

       * use the current input port if PORT_OR_FDES is not supplied.

       * read any characters that are currently available, without waiting for the rest (short reads are possible).

       * wait for as long as it needs to for the first character to become available, unless the port is in non-blocking mode

       * return #f if end-of-file is encountered before reading any characters, otherwise return the number of characters read.

       * return 0 if the port is in non-blocking mode and no characters are immediately available.

       * return 0 if the request is for 0 bytes, with no end-of-file check

Writing
=======

[Generic procedures for writing to ports.]

 -- primitive: get-print-state port
     Return the print state of the port PORT. If PORT has no associated print state, #f is returned.

 -- primitive: newline [port]
     Send a newline to PORT.

 -- primitive: port-with-print-state port pstate
     Create a new port which behaves like PORT, but with an included print state PSTATE.

 -- primitive: print-options-interface [setting]
     Option interface for the print options. Instead of using this procedure directly, use the procedures print-enable, print-disable, print-set! and print-options.

 -- primitive: simple-format destination message . args
     Write MESSAGE to DESTINATION, defaulting to the current output port. MESSAGE can contain ~A (was %s) and ~S (was %S) escapes.  When printed, the escapes are replaced with corresponding members of ARGS: ~A formats using display and ~S formats using write. If DESTINATION is #t, then use the current output port, if DESTINATION is #f, then return a string containing the formatted text. Does not add a trailing newline.

 -- primitive: write-char chr [port]
     Send character CHR to PORT.

 -- primitive: force-output [port]
     Flush the specified output port, or the current output port if PORT is omitted.  The current output buffer contents are passed to the underlying port implementation (e.g., in the case of fports, the data will be written to the file and the output buffer will be cleared.) It has no effect on an unbuffered port.

     The return value is unspecified.

 -- primitive: flush-all-ports
     Equivalent to calling force-output on all open output ports.  The return value is unspecified.

Closing
=======

 -- primitive: close-port port
     Close the specified port object.  Return #t if it successfully closes a port or #f if it was already closed.  An exception may be raised if an error occurs, for example when flushing buffered output.  See also close, for a procedure which can close file descriptors.

 -- primitive: close-input-port port
     Close the specified input port object.  The routine has no effect if the file has already been closed.  An exception may be raised if an error occurs.  The value returned is unspecified.

     See also close, for a procedure which can close file descriptors.

 -- primitive: close-output-port port
     Close the specified output port object.  The routine has no effect if the file has already been closed.  An exception may be raised if an error occurs.  The value returned is unspecified.

     See also close, for a procedure which can close file descriptors.

 -- primitive: port-closed? port
     Return #t if PORT is closed or #f if it is open.

Random Access
=============

 -- primitive: seek fd_port offset whence
     Sets the current position of FD/PORT to the integer OFFSET, which is interpreted according to the value of WHENCE. One of the following variables should be supplied for WHENCE:
      -- Variable: SEEK_SET
          Seek from the beginning of the file.

      -- Variable: SEEK_CUR
          Seek from the current position.

      -- Variable: SEEK_END
          Seek from the end of the file.

     If FD/PORT is a file descriptor, the underlying system call is lseek.  PORT may be a string port. The value returned is the new position in the file.  This means that the current position of a port can be obtained using:

          (seek port 0 SEEK_CUR)

 -- primitive: fseek fd_port offset whence
     Obsolete.  Almost the same as seek, but the return value is unspecified.

 -- primitive: ftell fd_port
     Return an integer representing the current position of FD/PORT, measured from the beginning.  Equivalent to:

          (seek port 0 SEEK_CUR)

 -- primitive: truncate-file object [length]
     Truncates the object referred to by OBJECT to at most LENGTH bytes.  OBJECT can be a string containing a file name or an integer file descriptor or a port. LENGTH may be omitted if OBJECT is not a file name, in which case the truncation occurs at the current port. position.  The return value is unspecified.

Handling Line Oriented and Delimited Text
=========================================

[Line-oriented and delimited IO.  Or should this be merged into the previous two sections?]

Extended I/O procedures are available which read or write lines of text or read text delimited by a specified set of characters.

Interfaces to read/fread and write/fwrite are also available, as uniform-array-read! and uniform-array-write!, Uniform Arrays.

 -- procedure: read-line [port] [handle-delim]
     Return a line of text from PORT if specified, otherwise from the value returned by (current-input-port).  Under Unix, a line of text is terminated by the first end-of-line character or by end-of-file.

     If HANDLE-DELIM is specified, it should be one of the following symbols:

     trim
          Discard the terminating delimiter.  This is the default, but it will be impossible to tell whether the read terminated with a delimiter or end-of-file.

     concat
          Append the terminating delimiter (if any) to the returned string.

     peek
          Push the terminating delimiter (if any) back on to the port.

     split
          Return a pair containing the string read from the port and the terminating delimiter or end-of-file object.

          NOTE: if the scsh module is loaded then multiple values are returned instead of a pair.

 -- procedure: read-line! buf [port]
     Read a line of text into the supplied string BUF and return the number of characters added to BUF.  If BUF is filled, then #f is returned. Read from PORT if specified, otherwise from the value returned by (current-input-port).

 -- procedure: read-delimited delims [port] [handle-delim]
     Read text until one of the characters in the string DELIMS is found or end-of-file is reached.  Read from PORT if supplied, otherwise from the value returned by (current-input-port). HANDLE-DELIM takes the same values as described for read-line.

     NOTE: if the scsh module is loaded then DELIMS must be an scsh char-set, not a string.

 -- procedure: read-delimited! delims buf [port] [handle-delim] [start] [end]
     Read text into the supplied string BUF and return the number of characters added to BUF (subject to HANDLE-DELIM, which takes the same values specified for read-line.  If BUF is filled, #f is returned for both the number of characters read and the delimiter.  Also terminates if one of the characters in the string DELIMS is found or end-of-file is reached.  Read from PORT if supplied, otherwise from the value returned by (current-input-port).

     NOTE: if the scsh module is loaded then DELIMS must be an scsh char-set, not a string.

 -- primitive: write-line obj [port]
     Display OBJ and a newline character to PORT.  If PORT is not specified, (current-output-port) is used.  This function is equivalent to:

          (display obj [port])
          (newline [port])

Some of the abovementioned I/O functions rely on the following C primitives.  These will mainly be of interest to people hacking Guile internals.

 -- primitive: %read-delimited! delims str gobble [port [start [end]]]
     Read characters from PORT into STR until one of the characters in the DELIMS string is encountered.  If GOBBLE is true, discard the delimiter character; otherwise, leave it in the input stream for the next read.  If PORT is not specified, use the value of (current-input-port).  If START or END are specified, store data only into the substring of STR bounded by START and END (which default to the beginning and end of the string, respectively). Return a pair consisting of the delimiter that terminated the string and the number of characters read.  If reading stopped at the end of file, the delimiter returned is the EOF-OBJECT; if the string was filled without encountering a delimiter, this value is #f.

 -- primitive: %read-line [port]
     Read a newline-terminated line from PORT, allocating storage as necessary.  The newline terminator (if any) is removed from the string, and a pair consisting of the line and its delimiter is returned.  The delimiter may be either a newline or the EOF-OBJECT; if %read-line is called at the end of file, it returns the pair (#<eof> . #<eof>).

Saving and Restoring Scheme Objects
===================================

 -- primitive: binary-read [port]
     Read and return an object from PORT in a binary format. If omitted, PORT defaults to the current output port.

 -- primitive: binary-write obj [port]
     Write OBJ to PORT in a binary format. If omitted, PORT defaults to the current output port.

Default Ports for Input, Output and Errors
==========================================

 -- primitive: current-input-port
     Return the current input port.  This is the default port used by many input procedures.  Initially, current-input-port returns the standard input in Unix and C terminology.

 -- primitive: current-output-port
     Return the current output port.  This is the default port used by many output procedures.  Initially, current-output-port returns the standard output in Unix and C terminology.

 -- primitive: current-error-port
     Return the port to which errors and warnings should be sent (the standard error in Unix and C terminology).

 -- primitive: set-current-input-port port
 -- primitive: set-current-output-port port
 -- primitive: set-current-error-port port
     Change the ports returned by current-input-port, current-output-port and current-error-port, respectively, so that they use the supplied PORT for input or output.

 -- primitive: set-current-output-port port
     Set the current default output port to PORT.

 -- primitive: set-current-error-port port
     Set the current default error port to PORT.

Types of Port
=============

[Types of port; how to make them.]

File Ports
----------

The following procedures are used to open file ports. See also open, for an interface to the Unix open system call.

 -- primitive: open-file filename mode
     Open the file whose name is FILENAME, and return a port representing that file.  The attributes of the port are determined by the MODE string.  The way in which this is interpreted is similar to C stdio.  The first character must be one of the following:

     r
          Open an existing file for input.

     w
          Open a file for output, creating it if it doesn't already exist or removing its contents if it does.

     a
          Open a file for output, creating it if it doesn't already exist.  All writes to the port will go to the end of the file. The "append mode" can be turned off while the port is in use see fcntl

     The following additional characters can be appended:

     +
          Open the port for both input and output.  E.g., r+: open an existing file for both input and output.

     0
          Create an "unbuffered" port.  In this case input and output operations are passed directly to the underlying port implementation without additional buffering.  This is likely to slow down I/O operations.  The buffering mode can be changed while a port is in use see setvbuf

     l
          Add line-buffering to the port.  The port output buffer will be automatically flushed whenever a newline character is written.

     In theory we could create read/write ports which were buffered in one direction only.  However this isn't included in the current interfaces.  If a file cannot be opened with the access requested, open-file throws an exception.

 -- procedure: open-input-file filename
     Open FILENAME for input.  Equivalent to

          (open-file FILENAME "r")

 -- procedure: open-output-file filename
     Open FILENAME for output.  Equivalent to

          (open-file FILENAME "w")

 -- procedure: call-with-input-file file proc
     PROC should be a procedure of one argument, and FILE should be a string naming a file.  The file must already exist. These procedures call PROC with one argument: the port obtained by opening the named file for input or output.  If the file cannot be opened, an error is signalled.  If the procedure returns, then the port is closed automatically and the value yielded by the procedure is returned.  If the procedure does not return, then the port will not be closed automatically unless it is possible to prove that the port will never again be used for a read or write operation.

 -- procedure: call-with-output-file file proc
     PROC should be a procedure of one argument, and FILE should be a string naming a file.  The behaviour is unspecified if the file already exists. These procedures call PROC with one argument: the port obtained by opening the named file for input or output.  If the file cannot be opened, an error is signalled.  If the procedure returns, then the port is closed automatically and the value yielded by the procedure is returned.  If the procedure does not return, then the port will not be closed automatically unless it is possible to prove that the port will never again be used for a read or write operation.

 -- procedure: with-input-from-file file thunk
     THUNK must be a procedure of no arguments, and FILE must be a string naming a file.  The file must already exist. The file is opened for input, an input port connected to it is made the default value returned by current-input-port, and the THUNK is called with no arguments.  When the THUNK returns, the port is closed and the previous default is restored.  Returns the value yielded by THUNK.  If an escape procedure is used to escape from the continuation of these procedures, their behavior is implementation dependent.

 -- procedure: with-output-to-file file thunk
     THUNK must be a procedure of no arguments, and FILE must be a string naming a file.  The effect is unspecified if the file already exists.  The file is opened for output, an output port connected to it is made the default value returned by current-output-port, and the THUNK is called with no arguments.  When the THUNK returns, the port is closed and the previous default is restored. Returns the value yielded by THUNK.  If an escape procedure is used to escape from the continuation of these procedures, their behavior is implementation dependent.

 -- procedure: with-error-to-file file thunk
     THUNK must be a procedure of no arguments, and FILE must be a string naming a file.  The effect is unspecified if the file already exists.  The file is opened for output, an output port connected to it is made the default value returned by current-error-port, and the THUNK is called with no arguments.  When the THUNK returns, the port is closed and the previous default is restored.  Returns the value yielded by THUNK.  If an escape procedure is used to escape from the continuation of these procedures, their behavior is implementation dependent.

 -- primitive: port-mode port
     Returns the port modes associated with the open port PORT.  These will not necessarily be identical to the modes used when the port was opened, since modes such as "append" which are used only during port creation are not retained.

 -- primitive: port-filename port
     Return the filename associated with PORT.  This function returns the strings "standard input", "standard output" and "standard error" when called on the current input, output and error ports respectively.

 -- primitive: set-port-filename! port filename
     Change the filename associated with PORT, using the current input port if none is specified.  Note that this does not change the port's source of data, but only the value that is returned by port-filename and reported in diagnostic output.

 -- primitive: file-port? obj
     Determine whether OBJ is a port that is related to a file.

String Ports
------------

The following allow string ports to be opened by analogy to R4R* file port facilities:

 -- primitive: call-with-output-string proc
     Calls the one-argument procedure PROC with a newly created output port.  When the function returns, the string composed of the characters written into the port is returned.

 -- primitive: call-with-input-string string proc
     Calls the one-argument procedure PROC with a newly created input port from which STRING's contents may be read.  The value yielded by the PROC is returned.

 -- procedure: with-output-to-string thunk
     Calls the zero-argument procedure THUNK with the current output port set temporarily to a new string port.  It returns a string composed of the characters written to the current output.

 -- procedure: with-input-from-string string thunk
     Calls the zero-argument procedure THUNK with the current input port set temporarily to a string port opened on the specified STRING.  The value yielded by THUNK is returned.

 -- primitive: open-input-string str
     Take a string and return an input port that delivers characters from the string. The port can be closed by close-input-port, though its storage will be reclaimed by the garbage collector if it becomes inaccessible.

 -- primitive: open-output-string
     Return an output port that will accumulate characters for retrieval by get-output-string. The port can be closed by the procedure close-output-port, though its storage will be reclaimed by the garbage collector if it becomes inaccessible.

 -- primitive: get-output-string port
     Given an output port created by open-output-string, return a string consisting of the characters that have been output to the port so far.

A string port can be used in many procedures which accept a port but which are not dependent on implementation details of fports. E.g., seeking and truncating will work on a string port, but trying to extract the file descriptor number will fail.

Soft Ports
----------

A soft-port is a port based on a vector of procedures capable of accepting or delivering characters.  It allows emulation of I/O ports.

 -- primitive: make-soft-port pv modes
     Return a port capable of receiving or delivering characters as specified by the MODES string (see open-file).  PV must be a vector of length 5.  Its components are as follows:

      0. procedure accepting one character for output

      1. procedure accepting a string for output

      2. thunk for flushing output

      3. thunk for getting one character

      4. thunk for closing port (not by garbage collection)

     For an output-only port only elements 0, 1, 2, and 4 need be procedures.  For an input-only port only elements 3 and 4 need be procedures.  Thunks 2 and 4 can instead be #f if there is no useful operation for them to perform. If thunk 3 returns #f or an eof-object (see eof-object? (The Revised^4 Report on Scheme)) it indicates that the port has reached end-of-file. For example:

          (define stdout (current-output-port))
          (define p (make-soft-port
                     (vector
                      (lambda (c) (write c stdout))
                      (lambda (s) (display s stdout))
                      (lambda () (display "." stdout))
                      (lambda () (char-upcase (read-char)))
                      (lambda () (display "@" stdout)))
                     "rw"))
          (write p p) => #<input-output: soft 8081e20>

Void Ports
----------

This kind of port causes any data to be discarded when written to, and always returns the end-of-file object when read from.

 -- primitive: %make-void-port mode
     Create and return a new void port.  A void port acts like /dev/null.  The MODE argument specifies the input/output modes for this port: see the documentation for open-file in File Ports.