3 @chapter Input and Output
6 * Ports:: The idea of the port abstraction.
7 * Reading:: Procedures for reading from a port.
8 * Writing:: Procedures for writing to a port.
9 * Closing:: Procedures to close a port.
10 * Random Access:: Moving around a random access port.
11 * Line/Delimited:: Read and write lines or delimited text.
12 * Binary IO:: Save and restore Scheme objects.
13 * Default Ports:: Defaults for input, output and errors.
14 * Port Types:: Types of port and how to make them.
21 [Concept of the port abstraction.]
23 Sequential input/output in Scheme is represented by operations on a
24 @dfn{port}. Characters can be read from an input port and
25 written to an output port. This chapter explains the operations
26 that Guile provides for working with ports.
28 The formal definition of a port is very generic: an input port is
29 simply ``an object which can deliver characters on command,'' and
30 an output port is ``an object which can accept characters.''
31 Because this definition is so loose, it is easy to write functions
32 that simulate ports in software. @dfn{Soft ports} and @dfn{string
33 ports} are two interesting and powerful examples of this technique.
36 @deffn primitive input-port? x
37 Return @code{#t} if @var{x} is an input port, otherwise return
38 @code{#f}. Any object satisfying this predicate also satisfies
43 @deffn primitive output-port? x
44 Return @code{#t} if @var{x} is an output port, otherwise return
45 @code{#f}. Any object satisfying this predicate also satisfies
49 @deffn primitive port? x
50 Return a boolean indicating whether @var{x} is a port.
51 Equivalent to @code{(or (input-port? @var{x}) (output-port?
59 [Generic procedures for reading from ports.]
62 @deffn primitive eof-object? x
63 Return @code{#t} if @var{x} is an end-of-file object; otherwise
68 @deffn primitive char-ready? [port]
69 Return @code{#t} if a character is ready on input @var{port}
70 and return @code{#f} otherwise. If @code{char-ready?} returns
71 @code{#t} then the next @code{read-char} operation on
72 @var{port} is guaranteed not to hang. If @var{port} is a file
73 port at end of file then @code{char-ready?} returns @code{#t}.
74 @footnote{@code{char-ready?} exists to make it possible for a
75 program to accept characters from interactive ports without
76 getting stuck waiting for input. Any input editors associated
77 with such ports must make sure that characters whose existence
78 has been asserted by @code{char-ready?} cannot be rubbed out.
79 If @code{char-ready?} were to return @code{#f} at end of file,
80 a port at end of file would be indistinguishable from an
81 interactive port that has no ready characters.}
85 @deffn primitive read-char [port]
86 Return the next character available from @var{port}, updating
87 @var{port} to point to the following character. If no more
88 characters are available, the end-of-file object is returned.
92 @deffn primitive peek-char [port]
93 Return the next character available from @var{port},
94 @emph{without} updating @var{port} to point to the following
95 character. If no more characters are available, the
96 end-of-file object is returned.@footnote{The value returned by
97 a call to @code{peek-char} is the same as the value that would
98 have been returned by a call to @code{read-char} on the same
99 port. The only difference is that the very next call to
100 @code{read-char} or @code{peek-char} on that @var{port} will
101 return the value returned by the preceding call to
102 @code{peek-char}. In particular, a call to @code{peek-char} on
103 an interactive port will hang waiting for input whenever a call
104 to @code{read-char} would have hung.}
107 @deffn primitive unread-char cobj port
108 Place @var{char} in @var{port} so that it will be read by the
109 next read operation. If called multiple times, the unread characters
110 will be read again in last-in first-out order. If @var{port} is
111 not supplied, the current input port is used.
114 @deffn primitive unread-string str port
115 Place the string @var{str} in @var{port} so that its characters will be
116 read in subsequent read operations. If called multiple times, the
117 unread characters will be read again in last-in first-out order. If
118 @var{port} is not supplied, the current-input-port is used.
121 @deffn primitive drain-input port
122 Drain @var{port}'s read buffers (including any pushed-back
123 characters) and return the content as a single string.
126 @deffn primitive port-column port
127 @deffnx primitive port-line port
128 Return the current column number or line number of @var{port},
129 using the current input port if none is specified. If the number is
130 unknown, the result is #f. Otherwise, the result is a 0-origin integer
131 - i.e. the first character of the first line is line 0, column 0.
132 (However, when you display a file position, for example in an error
133 message, we recommend you add 1 to get 1-origin integers. This is
134 because lines and column numbers traditionally start with 1, and that is
135 what non-programmers will find most natural.)
138 @deffn primitive set-port-column! port column
139 @deffnx primitive set-port-line! port line
140 Set the current column or line number of @var{port}, using the
141 current input port if none is specified.
144 @deffn primitive read-string!/partial str [port_or_fdes [start [end]]]
145 Read characters from an fport or file descriptor into a
146 string @var{str}. This procedure is scsh-compatible
147 and can efficiently read large strings. It will:
151 attempt to fill the entire string, unless the @var{start}
152 and/or @var{end} arguments are supplied. i.e., @var{start}
153 defaults to 0 and @var{end} defaults to
154 @code{(string-length str)}
156 use the current input port if @var{port_or_fdes} is not
159 read any characters that are currently available,
160 without waiting for the rest (short reads are possible).
163 wait for as long as it needs to for the first character to
164 become available, unless the port is in non-blocking mode
166 return @code{#f} if end-of-file is encountered before reading
167 any characters, otherwise return the number of characters
170 return 0 if the port is in non-blocking mode and no characters
171 are immediately available.
173 return 0 if the request is for 0 bytes, with no
182 [Generic procedures for writing to ports.]
184 @deffn primitive get-print-state port
185 Return the print state of the port @var{port}. If @var{port}
186 has no associated print state, @code{#f} is returned.
190 @deffn primitive newline [port]
191 Send a newline to @var{port}.
194 @deffn primitive port-with-print-state port pstate
195 Create a new port which behaves like @var{port}, but with an
196 included print state @var{pstate}.
199 @deffn primitive print-options-interface [setting]
200 Option interface for the print options. Instead of using
201 this procedure directly, use the procedures
202 @code{print-enable}, @code{print-disable}, @code{print-set!}
203 and @code{print-options}.
206 @deffn primitive simple-format destination message . args
207 Write @var{message} to @var{destination}, defaulting to
208 the current output port.
209 @var{message} can contain @code{~A} (was @code{%s}) and
210 @code{~S} (was @code{%S}) escapes. When printed,
211 the escapes are replaced with corresponding members of
213 @code{~A} formats using @code{display} and @code{~S} formats
215 If @var{destination} is @code{#t}, then use the current output
216 port, if @var{destination} is @code{#f}, then return a string
217 containing the formatted text. Does not add a trailing newline.
221 @deffn primitive write-char chr [port]
222 Send character @var{chr} to @var{port}.
226 @deffn primitive force-output [port]
227 Flush the specified output port, or the current output port if @var{port}
228 is omitted. The current output buffer contents are passed to the
229 underlying port implementation (e.g., in the case of fports, the
230 data will be written to the file and the output buffer will be cleared.)
231 It has no effect on an unbuffered port.
233 The return value is unspecified.
236 @deffn primitive flush-all-ports
237 Equivalent to calling @code{force-output} on
238 all open output ports. The return value is unspecified.
245 @deffn primitive close-port port
246 Close the specified port object. Return @code{#t} if it
247 successfully closes a port or @code{#f} if it was already
248 closed. An exception may be raised if an error occurs, for
249 example when flushing buffered output. See also @ref{Ports and
250 File Descriptors, close}, for a procedure which can close file
254 @rnindex close-input-port
255 @deffn primitive close-input-port port
256 Close the specified input port object. The routine has no effect if
257 the file has already been closed. An exception may be raised if an
258 error occurs. The value returned is unspecified.
260 See also @ref{Ports and File Descriptors, close}, for a procedure
261 which can close file descriptors.
264 @rnindex close-output-port
265 @deffn primitive close-output-port port
266 Close the specified output port object. The routine has no effect if
267 the file has already been closed. An exception may be raised if an
268 error occurs. The value returned is unspecified.
270 See also @ref{Ports and File Descriptors, close}, for a procedure
271 which can close file descriptors.
274 @deffn primitive port-closed? port
275 Return @code{#t} if @var{port} is closed or @code{#f} if it is
281 @section Random Access
283 @deffn primitive seek fd_port offset whence
284 Sets the current position of @var{fd/port} to the integer
285 @var{offset}, which is interpreted according to the value of
287 One of the following variables should be supplied for
290 Seek from the beginning of the file.
293 Seek from the current position.
296 Seek from the end of the file.
298 If @var{fd/port} is a file descriptor, the underlying system
299 call is @code{lseek}. @var{port} may be a string port.
300 The value returned is the new position in the file. This means
301 that the current position of a port can be obtained using:
303 (seek port 0 SEEK_CUR)
307 @deffn primitive fseek fd_port offset whence
308 Obsolete. Almost the same as @code{seek}, but the return value
312 @deffn primitive ftell fd_port
313 Return an integer representing the current position of
314 @var{fd/port}, measured from the beginning. Equivalent to:
316 (seek port 0 SEEK_CUR)
322 @deffn primitive truncate-file object [length]
323 Truncates the object referred to by @var{object} to at most
324 @var{length} bytes. @var{object} can be a string containing a
325 file name or an integer file descriptor or a port.
326 @var{length} may be omitted if @var{object} is not a file name,
327 in which case the truncation occurs at the current port.
328 position. The return value is unspecified.
333 @section Handling Line Oriented and Delimited Text
335 [Line-oriented and delimited IO. Or should this be merged into the
336 previous two sections?]
338 Extended I/O procedures are available which read or write lines of text
339 or read text delimited by a specified set of characters.
343 Interfaces to @code{read}/@code{fread} and @code{write}/@code{fwrite} are
344 also available, as @code{uniform-array-read!} and @code{uniform-array-write!},
345 @ref{Uniform Arrays}.
347 @c begin (scm-doc-string "boot-9.scm" "read-line")
348 @deffn procedure read-line [port] [handle-delim]
349 Return a line of text from @var{port} if specified, otherwise from the
350 value returned by @code{(current-input-port)}. Under Unix, a line of text
351 is terminated by the first end-of-line character or by end-of-file.
353 If @var{handle-delim} is specified, it should be one of the following
357 Discard the terminating delimiter. This is the default, but it will
358 be impossible to tell whether the read terminated with a delimiter or
361 Append the terminating delimiter (if any) to the returned string.
363 Push the terminating delimiter (if any) back on to the port.
365 Return a pair containing the string read from the port and the
366 terminating delimiter or end-of-file object.
368 NOTE: if the scsh module is loaded then
369 multiple values are returned instead of a pair.
373 @c begin (scm-doc-string "boot-9.scm" "read-line!")
374 @deffn procedure read-line! buf [port]
375 Read a line of text into the supplied string @var{buf} and return the
376 number of characters added to @var{buf}. If @var{buf} is filled, then
377 @code{#f} is returned.
378 Read from @var{port} if
379 specified, otherwise from the value returned by @code{(current-input-port)}.
382 @c begin (scm-doc-string "boot-9.scm" "read-delimited")
383 @deffn procedure read-delimited delims [port] [handle-delim]
384 Read text until one of the characters in the string @var{delims} is found
385 or end-of-file is reached. Read from @var{port} if supplied, otherwise
386 from the value returned by @code{(current-input-port)}.
387 @var{handle-delim} takes the same values as described for @code{read-line}.
389 NOTE: if the scsh module is loaded then @var{delims} must be an scsh
390 char-set, not a string.
393 @c begin (scm-doc-string "boot-9.scm" "read-delimited!")
394 @deffn procedure read-delimited! delims buf [port] [handle-delim] [start] [end]
395 Read text into the supplied string @var{buf} and return the number of
396 characters added to @var{buf} (subject to @var{handle-delim}, which takes
397 the same values specified for @code{read-line}. If @var{buf} is filled,
398 @code{#f} is returned for both the number of characters read and the
399 delimiter. Also terminates if one of the characters in the string
400 @var{delims} is found
401 or end-of-file is reached. Read from @var{port} if supplied, otherwise
402 from the value returned by @code{(current-input-port)}.
404 NOTE: if the scsh module is loaded then @var{delims} must be an scsh
405 char-set, not a string.
408 @deffn primitive write-line obj [port]
409 Display @var{obj} and a newline character to @var{port}. If
410 @var{port} is not specified, @code{(current-output-port)} is
411 used. This function is equivalent to:
418 Some of the abovementioned I/O functions rely on the following C
419 primitives. These will mainly be of interest to people hacking Guile
422 @deffn primitive %read-delimited! delims str gobble [port [start [end]]]
423 Read characters from @var{port} into @var{str} until one of the
424 characters in the @var{delims} string is encountered. If
425 @var{gobble} is true, discard the delimiter character;
426 otherwise, leave it in the input stream for the next read. If
427 @var{port} is not specified, use the value of
428 @code{(current-input-port)}. If @var{start} or @var{end} are
429 specified, store data only into the substring of @var{str}
430 bounded by @var{start} and @var{end} (which default to the
431 beginning and end of the string, respectively).
432 Return a pair consisting of the delimiter that terminated the
433 string and the number of characters read. If reading stopped
434 at the end of file, the delimiter returned is the
435 @var{eof-object}; if the string was filled without encountering
436 a delimiter, this value is @code{#f}.
439 @deffn primitive %read-line [port]
440 Read a newline-terminated line from @var{port}, allocating storage as
441 necessary. The newline terminator (if any) is removed from the string,
442 and a pair consisting of the line and its delimiter is returned. The
443 delimiter may be either a newline or the @var{eof-object}; if
444 @code{%read-line} is called at the end of file, it returns the pair
445 @code{(#<eof> . #<eof>)}.
449 @section Saving and Restoring Scheme Objects
451 @deffn primitive binary-read [port]
452 Read and return an object from @var{port} in a binary format.
453 If omitted, @var{port} defaults to the current output port.
456 @deffn primitive binary-write obj [port]
457 Write @var{obj} to @var{port} in a binary format.
458 If omitted, @var{port} defaults to the current output port.
463 @section Default Ports for Input, Output and Errors
465 @rnindex current-input-port
466 @deffn primitive current-input-port
467 Return the current input port. This is the default port used
468 by many input procedures. Initially, @code{current-input-port}
469 returns the @dfn{standard input} in Unix and C terminology.
472 @rnindex current-output-port
473 @deffn primitive current-output-port
474 Return the current output port. This is the default port used
475 by many output procedures. Initially,
476 @code{current-output-port} returns the @dfn{standard output} in
477 Unix and C terminology.
480 @deffn primitive current-error-port
481 Return the port to which errors and warnings should be sent (the
482 @dfn{standard error} in Unix and C terminology).
485 @deffn primitive set-current-input-port port
486 @deffnx primitive set-current-output-port port
487 @deffnx primitive set-current-error-port port
488 Change the ports returned by @code{current-input-port},
489 @code{current-output-port} and @code{current-error-port}, respectively,
490 so that they use the supplied @var{port} for input or output.
493 @deffn primitive set-current-output-port port
494 Set the current default output port to PORT.
497 @deffn primitive set-current-error-port port
498 Set the current default error port to PORT.
503 @section Types of Port
505 [Types of port; how to make them.]
508 * File Ports:: Ports on an operating system file.
509 * String Ports:: Ports on a Scheme string.
510 * Soft Ports:: Ports on arbitrary Scheme procedures.
511 * Void Ports:: Ports on nothing at all.
516 @subsection File Ports
518 The following procedures are used to open file ports.
519 See also @ref{Ports and File Descriptors, open}, for an interface
520 to the Unix @code{open} system call.
522 @deffn primitive open-file filename mode
523 Open the file whose name is @var{filename}, and return a port
524 representing that file. The attributes of the port are
525 determined by the @var{mode} string. The way in which this is
526 interpreted is similar to C stdio. The first character must be
527 one of the following:
530 Open an existing file for input.
532 Open a file for output, creating it if it doesn't already exist
533 or removing its contents if it does.
535 Open a file for output, creating it if it doesn't already
536 exist. All writes to the port will go to the end of the file.
537 The "append mode" can be turned off while the port is in use
538 @pxref{Ports and File Descriptors, fcntl}
540 The following additional characters can be appended:
543 Open the port for both input and output. E.g., @code{r+}: open
544 an existing file for both input and output.
546 Create an "unbuffered" port. In this case input and output
547 operations are passed directly to the underlying port
548 implementation without additional buffering. This is likely to
549 slow down I/O operations. The buffering mode can be changed
550 while a port is in use @pxref{Ports and File Descriptors,
553 Add line-buffering to the port. The port output buffer will be
554 automatically flushed whenever a newline character is written.
556 In theory we could create read/write ports which were buffered
557 in one direction only. However this isn't included in the
558 current interfaces. If a file cannot be opened with the access
559 requested, @code{open-file} throws an exception.
562 @rnindex open-input-file
563 @c begin (scm-doc-string "r4rs.scm" "open-input-file")
564 @deffn procedure open-input-file filename
565 Open @var{filename} for input. Equivalent to
567 (open-file @var{filename} "r")
571 @rnindex open-output-file
572 @c begin (scm-doc-string "r4rs.scm" "open-output-file")
573 @deffn procedure open-output-file filename
574 Open @var{filename} for output. Equivalent to
576 (open-file @var{filename} "w")
580 @rnindex call-with-input-file
581 @c begin (scm-doc-string "r4rs.scm" "call-with-input-file")
582 @deffn procedure call-with-input-file file proc
583 @var{proc} should be a procedure of one argument, and @var{file} should
584 be a string naming a file. The file must already exist. These
585 procedures call @var{proc} with one argument: the port obtained by
586 opening the named file for input or output. If the file cannot be
587 opened, an error is signalled. If the procedure returns, then the port
588 is closed automatically and the value yielded by the procedure is
589 returned. If the procedure does not return, then the port will not be
590 closed automatically unless it is possible to prove that the port will
591 never again be used for a read or write operation.
594 @rnindex call-with-output-file
595 @c begin (scm-doc-string "r4rs.scm" "call-with-output-file")
596 @deffn procedure call-with-output-file file proc
597 @var{proc} should be a procedure of one argument, and @var{file} should
598 be a string naming a file. The behaviour is unspecified if the file
599 already exists. These procedures call @var{proc} with one argument: the
600 port obtained by opening the named file for input or output. If the
601 file cannot be opened, an error is signalled. If the procedure returns,
602 then the port is closed automatically and the value yielded by the
603 procedure is returned. If the procedure does not return, then the port
604 will not be closed automatically unless it is possible to prove that the
605 port will never again be used for a read or write operation.
608 @rnindex with-input-from-file
609 @c begin (scm-doc-string "r4rs.scm" "with-input-from-file")
610 @deffn procedure with-input-from-file file thunk
611 @var{thunk} must be a procedure of no arguments, and @var{file} must be
612 a string naming a file. The file must already exist. The file is opened
613 for input, an input port connected to it is made the default value
614 returned by @code{current-input-port}, and the @var{thunk} is called
615 with no arguments. When the @var{thunk} returns, the port is closed and
616 the previous default is restored. Returns the value yielded by
617 @var{thunk}. If an escape procedure is used to escape from the
618 continuation of these procedures, their behavior is implementation
622 @rnindex with-output-to-file
623 @c begin (scm-doc-string "r4rs.scm" "with-output-to-file")
624 @deffn procedure with-output-to-file file thunk
625 @var{thunk} must be a procedure of no arguments, and @var{file} must be
626 a string naming a file. The effect is unspecified if the file already
627 exists. The file is opened for output, an output port connected to it
628 is made the default value returned by @code{current-output-port}, and
629 the @var{thunk} is called with no arguments. When the @var{thunk}
630 returns, the port is closed and the previous default is restored.
631 Returns the value yielded by @var{thunk}. If an escape procedure is
632 used to escape from the continuation of these procedures, their behavior
633 is implementation dependent.
636 @c begin (scm-doc-string "r4rs.scm" "with-error-to-file")
637 @deffn procedure with-error-to-file file thunk
638 @var{thunk} must be a procedure of no arguments, and @var{file} must be
639 a string naming a file. The effect is unspecified if the file already
640 exists. The file is opened for output, an output port connected to it
641 is made the default value returned by @code{current-error-port}, and the
642 @var{thunk} is called with no arguments. When the @var{thunk} returns,
643 the port is closed and the previous default is restored. Returns the
644 value yielded by @var{thunk}. If an escape procedure is used to escape
645 from the continuation of these procedures, their behavior is
646 implementation dependent.
649 @deffn primitive port-mode port
650 Returns the port modes associated with the open port @var{port}. These
651 will not necessarily be identical to the modes used when the port was
652 opened, since modes such as "append" which are used only during
653 port creation are not retained.
656 @deffn primitive port-filename port
657 Return the filename associated with @var{port}. This function returns
658 the strings "standard input", "standard output" and "standard error"
659 when called on the current input, output and error ports respectively.
662 @deffn primitive set-port-filename! port filename
663 Change the filename associated with @var{port}, using the current input
664 port if none is specified. Note that this does not change the port's
665 source of data, but only the value that is returned by
666 @code{port-filename} and reported in diagnostic output.
669 @deffn primitive file-port? obj
670 Determine whether @var{obj} is a port that is related to a file.
675 @subsection String Ports
677 The following allow string ports to be opened by analogy to R4R*
678 file port facilities:
680 @deffn primitive call-with-output-string proc
681 Calls the one-argument procedure @var{proc} with a newly created output
682 port. When the function returns, the string composed of the characters
683 written into the port is returned.
686 @deffn primitive call-with-input-string string proc
687 Calls the one-argument procedure @var{proc} with a newly
688 created input port from which @var{string}'s contents may be
689 read. The value yielded by the @var{proc} is returned.
692 @c begin (scm-doc-string "r4rs.scm" "with-output-to-string")
693 @deffn procedure with-output-to-string thunk
694 Calls the zero-argument procedure @var{thunk} with the current output
695 port set temporarily to a new string port. It returns a string
696 composed of the characters written to the current output.
699 @c begin (scm-doc-string "r4rs.scm" "with-input-from-string")
700 @deffn procedure with-input-from-string string thunk
701 Calls the zero-argument procedure @var{thunk} with the current input
702 port set temporarily to a string port opened on the specified
703 @var{string}. The value yielded by @var{thunk} is returned.
706 @deffn primitive open-input-string str
707 Take a string and return an input port that delivers characters
708 from the string. The port can be closed by
709 @code{close-input-port}, though its storage will be reclaimed
710 by the garbage collector if it becomes inaccessible.
713 @deffn primitive open-output-string
714 Return an output port that will accumulate characters for
715 retrieval by @code{get-output-string}. The port can be closed
716 by the procedure @code{close-output-port}, though its storage
717 will be reclaimed by the garbage collector if it becomes
721 @deffn primitive get-output-string port
722 Given an output port created by @code{open-output-string},
723 return a string consisting of the characters that have been
724 output to the port so far.
727 A string port can be used in many procedures which accept a port
728 but which are not dependent on implementation details of fports.
729 E.g., seeking and truncating will work on a string port,
730 but trying to extract the file descriptor number will fail.
734 @subsection Soft Ports
736 A @dfn{soft-port} is a port based on a vector of procedures capable of
737 accepting or delivering characters. It allows emulation of I/O ports.
739 @deffn primitive make-soft-port pv modes
740 Return a port capable of receiving or delivering characters as
741 specified by the @var{modes} string (@pxref{File Ports,
742 open-file}). @var{pv} must be a vector of length 5. Its
743 components are as follows:
746 procedure accepting one character for output
748 procedure accepting a string for output
750 thunk for flushing output
752 thunk for getting one character
754 thunk for closing port (not by garbage collection)
756 For an output-only port only elements 0, 1, 2, and 4 need be
757 procedures. For an input-only port only elements 3 and 4 need
758 be procedures. Thunks 2 and 4 can instead be @code{#f} if
759 there is no useful operation for them to perform.
760 If thunk 3 returns @code{#f} or an @code{eof-object}
761 (@pxref{Input, eof-object?, ,r4rs, The Revised^4 Report on
762 Scheme}) it indicates that the port has reached end-of-file.
765 (define stdout (current-output-port))
766 (define p (make-soft-port
768 (lambda (c) (write c stdout))
769 (lambda (s) (display s stdout))
770 (lambda () (display "." stdout))
771 (lambda () (char-upcase (read-char)))
772 (lambda () (display "@@" stdout)))
774 (write p p) @result{} #<input-output: soft 8081e20>
780 @subsection Void Ports
782 This kind of port causes any data to be discarded when written to, and
783 always returns the end-of-file object when read from.
785 @deffn primitive %make-void-port mode
786 Create and return a new void port. A void port acts like
787 /dev/null. The @var{mode} argument
788 specifies the input/output modes for this port: see the
789 documentation for @code{open-file} in @ref{File Ports}.
794 @c TeX-master: "guile.texi"