2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
9 @section Input and Output
12 * Ports:: The idea of the port abstraction.
13 * Reading:: Procedures for reading from a port.
14 * Writing:: Procedures for writing to a port.
15 * Closing:: Procedures to close a port.
16 * Random Access:: Moving around a random access port.
17 * Line/Delimited:: Read and write lines or delimited text.
18 * Block Reading and Writing:: Reading and writing blocks of text.
19 * Default Ports:: Defaults for input, output and errors.
20 * Port Types:: Types of port and how to make them.
21 * I/O Extensions:: Using and extending ports in C.
29 Sequential input/output in Scheme is represented by operations on a
30 @dfn{port}. This chapter explains the operations that Guile provides
31 for working with ports.
33 Ports are created by opening, for instance @code{open-file} for a file
34 (@pxref{File Ports}). Characters can be read from an input port and
35 written to an output port, or both on an input/output port. A port
36 can be closed (@pxref{Closing}) when no longer required, after which
37 any attempt to read or write is an error.
39 The formal definition of a port is very generic: an input port is
40 simply ``an object which can deliver characters on demand,'' and an
41 output port is ``an object which can accept characters.'' Because
42 this definition is so loose, it is easy to write functions that
43 simulate ports in software. @dfn{Soft ports} and @dfn{string ports}
44 are two interesting and powerful examples of this technique.
45 (@pxref{Soft Ports}, and @ref{String Ports}.)
47 Ports are garbage collected in the usual way (@pxref{Memory
48 Management}), and will be closed at that time if not already closed.
49 In this case any errors occuring in the close will not be reported.
50 Usually a program will want to explicitly close so as to be sure all
51 its operations have been successful. Of course if a program has
52 abandoned something due to an error or other condition then closing
53 problems are probably not of interest.
55 It is strongly recommended that file ports be closed explicitly when
56 no longer required. Most systems have limits on how many files can be
57 open, both on a per-process and a system-wide basis. A program that
58 uses many files should take care not to hit those limits. The same
59 applies to similar system resources such as pipes and sockets.
61 Note that automatic garbage collection is triggered only by memory
62 consumption, not by file or other resource usage, so a program cannot
63 rely on that to keep it away from system limits. An explicit call to
64 @code{gc} can of course be relied on to pick up unreferenced ports.
65 If program flow makes it hard to be certain when to close then this
66 may be an acceptable way to control resource usage.
68 All file access uses the ``LFS'' large file support functions when
69 available, so files bigger than 2 Gbytes (@math{2^31} bytes) can be
70 read and written on a 32-bit system.
73 @deffn {Scheme Procedure} input-port? x
74 @deffnx {C Function} scm_input_port_p (x)
75 Return @code{#t} if @var{x} is an input port, otherwise return
76 @code{#f}. Any object satisfying this predicate also satisfies
81 @deffn {Scheme Procedure} output-port? x
82 @deffnx {C Function} scm_output_port_p (x)
83 Return @code{#t} if @var{x} is an output port, otherwise return
84 @code{#f}. Any object satisfying this predicate also satisfies
88 @deffn {Scheme Procedure} port? x
89 @deffnx {C Function} scm_port_p (x)
90 Return a boolean indicating whether @var{x} is a port.
91 Equivalent to @code{(or (input-port? @var{x}) (output-port?
100 [Generic procedures for reading from ports.]
103 @cindex End of file object
104 @deffn {Scheme Procedure} eof-object? x
105 @deffnx {C Function} scm_eof_object_p (x)
106 Return @code{#t} if @var{x} is an end-of-file object; otherwise
111 @deffn {Scheme Procedure} char-ready? [port]
112 @deffnx {C Function} scm_char_ready_p (port)
113 Return @code{#t} if a character is ready on input @var{port}
114 and return @code{#f} otherwise. If @code{char-ready?} returns
115 @code{#t} then the next @code{read-char} operation on
116 @var{port} is guaranteed not to hang. If @var{port} is a file
117 port at end of file then @code{char-ready?} returns @code{#t}.
119 @code{char-ready?} exists to make it possible for a
120 program to accept characters from interactive ports without
121 getting stuck waiting for input. Any input editors associated
122 with such ports must make sure that characters whose existence
123 has been asserted by @code{char-ready?} cannot be rubbed out.
124 If @code{char-ready?} were to return @code{#f} at end of file,
125 a port at end of file would be indistinguishable from an
126 interactive port that has no ready characters.
130 @deffn {Scheme Procedure} read-char [port]
131 @deffnx {C Function} scm_read_char (port)
132 Return the next character available from @var{port}, updating
133 @var{port} to point to the following character. If no more
134 characters are available, the end-of-file object is returned.
137 @deftypefn {C Function} size_t scm_c_read (SCM port, void *buffer, size_t size)
138 Read up to @var{size} bytes from @var{port} and store them in
139 @var{buffer}. The return value is the number of bytes actually read,
140 which can be less than @var{size} if end-of-file has been reached.
142 Note that this function does not update @code{port-line} and
143 @code{port-column} below.
147 @deffn {Scheme Procedure} peek-char [port]
148 @deffnx {C Function} scm_peek_char (port)
149 Return the next character available from @var{port},
150 @emph{without} updating @var{port} to point to the following
151 character. If no more characters are available, the
152 end-of-file object is returned.
154 The value returned by
155 a call to @code{peek-char} is the same as the value that would
156 have been returned by a call to @code{read-char} on the same
157 port. The only difference is that the very next call to
158 @code{read-char} or @code{peek-char} on that @var{port} will
159 return the value returned by the preceding call to
160 @code{peek-char}. In particular, a call to @code{peek-char} on
161 an interactive port will hang waiting for input whenever a call
162 to @code{read-char} would have hung.
165 @deffn {Scheme Procedure} unread-char cobj [port]
166 @deffnx {C Function} scm_unread_char (cobj, port)
167 Place @var{char} in @var{port} so that it will be read by the
168 next read operation. If called multiple times, the unread characters
169 will be read again in last-in first-out order. If @var{port} is
170 not supplied, the current input port is used.
173 @deffn {Scheme Procedure} unread-string str port
174 @deffnx {C Function} scm_unread_string (str, port)
175 Place the string @var{str} in @var{port} so that its characters will
176 be read from left-to-right as the next characters from @var{port}
177 during subsequent read operations. If called multiple times, the
178 unread characters will be read again in last-in first-out order. If
179 @var{port} is not supplied, the @code{current-input-port} is used.
182 @deffn {Scheme Procedure} drain-input port
183 @deffnx {C Function} scm_drain_input (port)
184 This procedure clears a port's input buffers, similar
185 to the way that force-output clears the output buffer. The
186 contents of the buffers are returned as a single string, e.g.,
189 (define p (open-input-file ...))
190 (drain-input p) => empty string, nothing buffered yet.
191 (unread-char (read-char p) p)
192 (drain-input p) => initial chars from p, up to the buffer size.
195 Draining the buffers may be useful for cleanly finishing
196 buffered I/O so that the file descriptor can be used directly
200 @deffn {Scheme Procedure} port-column port
201 @deffnx {Scheme Procedure} port-line port
202 @deffnx {C Function} scm_port_column (port)
203 @deffnx {C Function} scm_port_line (port)
204 Return the current column number or line number of @var{port}.
206 unknown, the result is #f. Otherwise, the result is a 0-origin integer
207 - i.e.@: the first character of the first line is line 0, column 0.
208 (However, when you display a file position, for example in an error
209 message, we recommend you add 1 to get 1-origin integers. This is
210 because lines and column numbers traditionally start with 1, and that is
211 what non-programmers will find most natural.)
214 @deffn {Scheme Procedure} set-port-column! port column
215 @deffnx {Scheme Procedure} set-port-line! port line
216 @deffnx {C Function} scm_set_port_column_x (port, column)
217 @deffnx {C Function} scm_set_port_line_x (port, line)
218 Set the current column or line number of @var{port}.
225 [Generic procedures for writing to ports.]
227 @deffn {Scheme Procedure} get-print-state port
228 @deffnx {C Function} scm_get_print_state (port)
229 Return the print state of the port @var{port}. If @var{port}
230 has no associated print state, @code{#f} is returned.
234 @deffn {Scheme Procedure} write obj [port]
235 Send a representation of @var{obj} to @var{port} or to the current
236 output port if not given.
238 The output is designed to be machine readable, and can be read back
239 with @code{read} (@pxref{Reading}). Strings are printed in
240 doublequotes, with escapes if necessary, and characters are printed in
245 @deffn {Scheme Procedure} display obj [port]
246 Send a representation of @var{obj} to @var{port} or to the current
247 output port if not given.
249 The output is designed for human readability, it differs from
250 @code{write} in that strings are printed without doublequotes and
251 escapes, and characters are printed as per @code{write-char}, not in
256 @deffn {Scheme Procedure} newline [port]
257 @deffnx {C Function} scm_newline (port)
258 Send a newline to @var{port}.
259 If @var{port} is omitted, send to the current output port.
262 @deffn {Scheme Procedure} port-with-print-state port [pstate]
263 @deffnx {C Function} scm_port_with_print_state (port, pstate)
264 Create a new port which behaves like @var{port}, but with an
265 included print state @var{pstate}. @var{pstate} is optional.
266 If @var{pstate} isn't supplied and @var{port} already has
267 a print state, the old print state is reused.
270 @deffn {Scheme Procedure} print-options-interface [setting]
271 @deffnx {C Function} scm_print_options (setting)
272 Option interface for the print options. Instead of using
273 this procedure directly, use the procedures
274 @code{print-enable}, @code{print-disable}, @code{print-set!}
275 and @code{print-options}.
278 @deffn {Scheme Procedure} simple-format destination message . args
279 @deffnx {C Function} scm_simple_format (destination, message, args)
280 Write @var{message} to @var{destination}, defaulting to
281 the current output port.
282 @var{message} can contain @code{~A} (was @code{%s}) and
283 @code{~S} (was @code{%S}) escapes. When printed,
284 the escapes are replaced with corresponding members of
286 @code{~A} formats using @code{display} and @code{~S} formats
288 If @var{destination} is @code{#t}, then use the current output
289 port, if @var{destination} is @code{#f}, then return a string
290 containing the formatted text. Does not add a trailing newline.
294 @deffn {Scheme Procedure} write-char chr [port]
295 @deffnx {C Function} scm_write_char (chr, port)
296 Send character @var{chr} to @var{port}.
299 @deftypefn {C Function} void scm_c_write (SCM port, const void *buffer, size_t size)
300 Write @var{size} bytes at @var{buffer} to @var{port}.
302 Note that this function does not update @code{port-line} and
303 @code{port-column} (@pxref{Reading}).
307 @deffn {Scheme Procedure} force-output [port]
308 @deffnx {C Function} scm_force_output (port)
309 Flush the specified output port, or the current output port if @var{port}
310 is omitted. The current output buffer contents are passed to the
311 underlying port implementation (e.g., in the case of fports, the
312 data will be written to the file and the output buffer will be cleared.)
313 It has no effect on an unbuffered port.
315 The return value is unspecified.
318 @deffn {Scheme Procedure} flush-all-ports
319 @deffnx {C Function} scm_flush_all_ports ()
320 Equivalent to calling @code{force-output} on
321 all open output ports. The return value is unspecified.
327 @cindex Closing ports
330 @deffn {Scheme Procedure} close-port port
331 @deffnx {C Function} scm_close_port (port)
332 Close the specified port object. Return @code{#t} if it
333 successfully closes a port or @code{#f} if it was already
334 closed. An exception may be raised if an error occurs, for
335 example when flushing buffered output. See also @ref{Ports and
336 File Descriptors, close}, for a procedure which can close file
340 @deffn {Scheme Procedure} close-input-port port
341 @deffnx {Scheme Procedure} close-output-port port
342 @deffnx {C Function} scm_close_input_port (port)
343 @deffnx {C Function} scm_close_output_port (port)
344 @rnindex close-input-port
345 @rnindex close-output-port
346 Close the specified input or output @var{port}. An exception may be
347 raised if an error occurs while closing. If @var{port} is already
348 closed, nothing is done. The return value is unspecified.
350 See also @ref{Ports and File Descriptors, close}, for a procedure
351 which can close file descriptors.
354 @deffn {Scheme Procedure} port-closed? port
355 @deffnx {C Function} scm_port_closed_p (port)
356 Return @code{#t} if @var{port} is closed or @code{#f} if it is
362 @subsection Random Access
363 @cindex Random access, ports
364 @cindex Port, random access
366 @deffn {Scheme Procedure} seek fd_port offset whence
367 @deffnx {C Function} scm_seek (fd_port, offset, whence)
368 Sets the current position of @var{fd/port} to the integer
369 @var{offset}, which is interpreted according to the value of
372 One of the following variables should be supplied for
375 Seek from the beginning of the file.
378 Seek from the current position.
381 Seek from the end of the file.
383 If @var{fd/port} is a file descriptor, the underlying system
384 call is @code{lseek}. @var{port} may be a string port.
386 The value returned is the new position in the file. This means
387 that the current position of a port can be obtained using:
389 (seek port 0 SEEK_CUR)
393 @deffn {Scheme Procedure} ftell fd_port
394 @deffnx {C Function} scm_ftell (fd_port)
395 Return an integer representing the current position of
396 @var{fd/port}, measured from the beginning. Equivalent to:
399 (seek port 0 SEEK_CUR)
405 @deffn {Scheme Procedure} truncate-file file [length]
406 @deffnx {C Function} scm_truncate_file (file, length)
407 Truncate @var{file} to @var{length} bytes. @var{file} can be a
408 filename string, a port object, or an integer file descriptor. The
409 return value is unspecified.
411 For a port or file descriptor @var{length} can be omitted, in which
412 case the file is truncated at the current position (per @code{ftell}
415 On most systems a file can be extended by giving a length greater than
416 the current size, but this is not mandatory in the POSIX standard.
420 @subsection Line Oriented and Delimited Text
421 @cindex Line input/output
422 @cindex Port, line input/output
424 The delimited-I/O module can be accessed with:
427 (use-modules (ice-9 rdelim))
430 It can be used to read or write lines of text, or read text delimited by
431 a specified set of characters. It's similar to the @code{(scsh rdelim)}
432 module from guile-scsh, but does not use multiple values or character
433 sets and has an extra procedure @code{write-line}.
435 @c begin (scm-doc-string "rdelim.scm" "read-line")
436 @deffn {Scheme Procedure} read-line [port] [handle-delim]
437 Return a line of text from @var{port} if specified, otherwise from the
438 value returned by @code{(current-input-port)}. Under Unix, a line of text
439 is terminated by the first end-of-line character or by end-of-file.
441 If @var{handle-delim} is specified, it should be one of the following
445 Discard the terminating delimiter. This is the default, but it will
446 be impossible to tell whether the read terminated with a delimiter or
449 Append the terminating delimiter (if any) to the returned string.
451 Push the terminating delimiter (if any) back on to the port.
453 Return a pair containing the string read from the port and the
454 terminating delimiter or end-of-file object.
458 @c begin (scm-doc-string "rdelim.scm" "read-line!")
459 @deffn {Scheme Procedure} read-line! buf [port]
460 Read a line of text into the supplied string @var{buf} and return the
461 number of characters added to @var{buf}. If @var{buf} is filled, then
462 @code{#f} is returned.
463 Read from @var{port} if
464 specified, otherwise from the value returned by @code{(current-input-port)}.
467 @c begin (scm-doc-string "rdelim.scm" "read-delimited")
468 @deffn {Scheme Procedure} read-delimited delims [port] [handle-delim]
469 Read text until one of the characters in the string @var{delims} is found
470 or end-of-file is reached. Read from @var{port} if supplied, otherwise
471 from the value returned by @code{(current-input-port)}.
472 @var{handle-delim} takes the same values as described for @code{read-line}.
475 @c begin (scm-doc-string "rdelim.scm" "read-delimited!")
476 @deffn {Scheme Procedure} read-delimited! delims buf [port] [handle-delim] [start] [end]
477 Read text into the supplied string @var{buf} and return the number of
478 characters added to @var{buf} (subject to @var{handle-delim}, which takes
479 the same values specified for @code{read-line}. If @var{buf} is filled,
480 @code{#f} is returned for both the number of characters read and the
481 delimiter. Also terminates if one of the characters in the string
482 @var{delims} is found
483 or end-of-file is reached. Read from @var{port} if supplied, otherwise
484 from the value returned by @code{(current-input-port)}.
487 @deffn {Scheme Procedure} write-line obj [port]
488 @deffnx {C Function} scm_write_line (obj, port)
489 Display @var{obj} and a newline character to @var{port}. If
490 @var{port} is not specified, @code{(current-output-port)} is
491 used. This function is equivalent to:
498 Some of the abovementioned I/O functions rely on the following C
499 primitives. These will mainly be of interest to people hacking Guile
502 @deffn {Scheme Procedure} %read-delimited! delims str gobble [port [start [end]]]
503 @deffnx {C Function} scm_read_delimited_x (delims, str, gobble, port, start, end)
504 Read characters from @var{port} into @var{str} until one of the
505 characters in the @var{delims} string is encountered. If
506 @var{gobble} is true, discard the delimiter character;
507 otherwise, leave it in the input stream for the next read. If
508 @var{port} is not specified, use the value of
509 @code{(current-input-port)}. If @var{start} or @var{end} are
510 specified, store data only into the substring of @var{str}
511 bounded by @var{start} and @var{end} (which default to the
512 beginning and end of the string, respectively).
514 Return a pair consisting of the delimiter that terminated the
515 string and the number of characters read. If reading stopped
516 at the end of file, the delimiter returned is the
517 @var{eof-object}; if the string was filled without encountering
518 a delimiter, this value is @code{#f}.
521 @deffn {Scheme Procedure} %read-line [port]
522 @deffnx {C Function} scm_read_line (port)
523 Read a newline-terminated line from @var{port}, allocating storage as
524 necessary. The newline terminator (if any) is removed from the string,
525 and a pair consisting of the line and its delimiter is returned. The
526 delimiter may be either a newline or the @var{eof-object}; if
527 @code{%read-line} is called at the end of file, it returns the pair
528 @code{(#<eof> . #<eof>)}.
531 @node Block Reading and Writing
532 @subsection Block reading and writing
533 @cindex Block read/write
534 @cindex Port, block read/write
536 The Block-string-I/O module can be accessed with:
539 (use-modules (ice-9 rw))
542 It currently contains procedures that help to implement the
543 @code{(scsh rw)} module in guile-scsh.
545 @deffn {Scheme Procedure} read-string!/partial str [port_or_fdes [start [end]]]
546 @deffnx {C Function} scm_read_string_x_partial (str, port_or_fdes, start, end)
547 Read characters from a port or file descriptor into a
548 string @var{str}. A port must have an underlying file
549 descriptor --- a so-called fport. This procedure is
550 scsh-compatible and can efficiently read large strings.
555 attempt to fill the entire string, unless the @var{start}
556 and/or @var{end} arguments are supplied. i.e., @var{start}
557 defaults to 0 and @var{end} defaults to
558 @code{(string-length str)}
560 use the current input port if @var{port_or_fdes} is not
563 return fewer than the requested number of characters in some
564 cases, e.g., on end of file, if interrupted by a signal, or if
565 not all the characters are immediately available.
567 wait indefinitely for some input if no characters are
569 unless the port is in non-blocking mode.
571 read characters from the port's input buffers if available,
572 instead from the underlying file descriptor.
574 return @code{#f} if end-of-file is encountered before reading
575 any characters, otherwise return the number of characters
578 return 0 if the port is in non-blocking mode and no characters
579 are immediately available.
581 return 0 if the request is for 0 bytes, with no
586 @deffn {Scheme Procedure} write-string/partial str [port_or_fdes [start [end]]]
587 @deffnx {C Function} scm_write_string_partial (str, port_or_fdes, start, end)
588 Write characters from a string @var{str} to a port or file
589 descriptor. A port must have an underlying file descriptor
590 --- a so-called fport. This procedure is
591 scsh-compatible and can efficiently write large strings.
596 attempt to write the entire string, unless the @var{start}
597 and/or @var{end} arguments are supplied. i.e., @var{start}
598 defaults to 0 and @var{end} defaults to
599 @code{(string-length str)}
601 use the current output port if @var{port_of_fdes} is not
604 in the case of a buffered port, store the characters in the
605 port's output buffer, if all will fit. If they will not fit
606 then any existing buffered characters will be flushed
608 to write the new characters directly to the underlying file
609 descriptor. If the port is in non-blocking mode and
610 buffered characters can not be flushed immediately, then an
611 @code{EAGAIN} system-error exception will be raised (Note:
612 scsh does not support the use of non-blocking buffered ports.)
614 write fewer than the requested number of
615 characters in some cases, e.g., if interrupted by a signal or
616 if not all of the output can be accepted immediately.
618 wait indefinitely for at least one character
619 from @var{str} to be accepted by the port, unless the port is
620 in non-blocking mode.
622 return the number of characters accepted by the port.
624 return 0 if the port is in non-blocking mode and can not accept
625 at least one character from @var{str} immediately
627 return 0 immediately if the request size is 0 bytes.
632 @subsection Default Ports for Input, Output and Errors
633 @cindex Default ports
634 @cindex Port, default
636 @rnindex current-input-port
637 @deffn {Scheme Procedure} current-input-port
638 @deffnx {C Function} scm_current_input_port ()
639 @cindex standard input
640 Return the current input port. This is the default port used
641 by many input procedures.
643 Initially this is the @dfn{standard input} in Unix and C terminology.
644 When the standard input is a tty the port is unbuffered, otherwise
647 Unbuffered input is good if an application runs an interactive
648 subprocess, since any type-ahead input won't go into Guile's buffer
649 and be unavailable to the subprocess.
651 Note that Guile buffering is completely separate from the tty ``line
652 discipline''. In the usual cooked mode on a tty Guile only sees a
653 line of input once the user presses @key{Return}.
656 @rnindex current-output-port
657 @deffn {Scheme Procedure} current-output-port
658 @deffnx {C Function} scm_current_output_port ()
659 @cindex standard output
660 Return the current output port. This is the default port used
661 by many output procedures.
663 Initially this is the @dfn{standard output} in Unix and C terminology.
664 When the standard output is a tty this port is unbuffered, otherwise
667 Unbuffered output to a tty is good for ensuring progress output or a
668 prompt is seen. But an application which always prints whole lines
669 could change to line buffered, or an application with a lot of output
670 could go fully buffered and perhaps make explicit @code{force-output}
671 calls (@pxref{Writing}) at selected points.
674 @deffn {Scheme Procedure} current-error-port
675 @deffnx {C Function} scm_current_error_port ()
676 @cindex standard error output
677 Return the port to which errors and warnings should be sent.
679 Initially this is the @dfn{standard error} in Unix and C terminology.
680 When the standard error is a tty this port is unbuffered, otherwise
684 @deffn {Scheme Procedure} set-current-input-port port
685 @deffnx {Scheme Procedure} set-current-output-port port
686 @deffnx {Scheme Procedure} set-current-error-port port
687 @deffnx {C Function} scm_set_current_input_port (port)
688 @deffnx {C Function} scm_set_current_output_port (port)
689 @deffnx {C Function} scm_set_current_error_port (port)
690 Change the ports returned by @code{current-input-port},
691 @code{current-output-port} and @code{current-error-port}, respectively,
692 so that they use the supplied @var{port} for input or output.
695 @deftypefn {C Function} void scm_dynwind_current_input_port (SCM port)
696 @deftypefnx {C Function} void scm_dynwind_current_output_port (SCM port)
697 @deftypefnx {C Function} void scm_dynwind_current_error_port (SCM port)
698 These functions must be used inside a pair of calls to
699 @code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
700 Wind}). During the dynwind context, the indicated port is set to
703 More precisely, the current port is swapped with a `backup' value
704 whenever the dynwind context is entered or left. The backup value is
705 initialized with the @var{port} argument.
709 @subsection Types of Port
710 @cindex Types of ports
713 [Types of port; how to make them.]
716 * File Ports:: Ports on an operating system file.
717 * String Ports:: Ports on a Scheme string.
718 * Soft Ports:: Ports on arbitrary Scheme procedures.
719 * Void Ports:: Ports on nothing at all.
724 @subsubsection File Ports
728 The following procedures are used to open file ports.
729 See also @ref{Ports and File Descriptors, open}, for an interface
730 to the Unix @code{open} system call.
732 Most systems have limits on how many files can be open, so it's
733 strongly recommended that file ports be closed explicitly when no
734 longer required (@pxref{Ports}).
736 @deffn {Scheme Procedure} open-file filename mode
737 @deffnx {C Function} scm_open_file (filename, mode)
738 Open the file whose name is @var{filename}, and return a port
739 representing that file. The attributes of the port are
740 determined by the @var{mode} string. The way in which this is
741 interpreted is similar to C stdio. The first character must be
742 one of the following:
746 Open an existing file for input.
748 Open a file for output, creating it if it doesn't already exist
749 or removing its contents if it does.
751 Open a file for output, creating it if it doesn't already
752 exist. All writes to the port will go to the end of the file.
753 The "append mode" can be turned off while the port is in use
754 @pxref{Ports and File Descriptors, fcntl}
757 The following additional characters can be appended:
761 Open the port for both input and output. E.g., @code{r+}: open
762 an existing file for both input and output.
764 Create an "unbuffered" port. In this case input and output
765 operations are passed directly to the underlying port
766 implementation without additional buffering. This is likely to
767 slow down I/O operations. The buffering mode can be changed
768 while a port is in use @pxref{Ports and File Descriptors,
771 Add line-buffering to the port. The port output buffer will be
772 automatically flushed whenever a newline character is written.
774 Use binary mode. On DOS systems the default text mode converts CR+LF
775 in the file to newline for the program, whereas binary mode reads and
776 writes all bytes unchanged. On Unix-like systems there is no such
777 distinction, text files already contain just newlines and no
778 conversion is ever made. The @code{b} flag is accepted on all
779 systems, but has no effect on Unix-like systems.
781 (For reference, Guile leaves text versus binary up to the C library,
782 @code{b} here just adds @code{O_BINARY} to the underlying @code{open}
783 call, when that flag is available.)
786 If a file cannot be opened with the access
787 requested, @code{open-file} throws an exception.
789 In theory we could create read/write ports which were buffered
790 in one direction only. However this isn't included in the
794 @rnindex open-input-file
795 @deffn {Scheme Procedure} open-input-file filename
796 Open @var{filename} for input. Equivalent to
798 (open-file @var{filename} "r")
802 @rnindex open-output-file
803 @deffn {Scheme Procedure} open-output-file filename
804 Open @var{filename} for output. Equivalent to
806 (open-file @var{filename} "w")
810 @deffn {Scheme Procedure} call-with-input-file filename proc
811 @deffnx {Scheme Procedure} call-with-output-file filename proc
812 @rnindex call-with-input-file
813 @rnindex call-with-output-file
814 Open @var{filename} for input or output, and call @code{(@var{proc}
815 port)} with the resulting port. Return the value returned by
816 @var{proc}. @var{filename} is opened as per @code{open-input-file} or
817 @code{open-output-file} respectively, and an error is signalled if it
820 When @var{proc} returns, the port is closed. If @var{proc} does not
821 return (eg.@: if it throws an error), then the port might not be
822 closed automatically, though it will be garbage collected in the usual
823 way if not otherwise referenced.
826 @deffn {Scheme Procedure} with-input-from-file filename thunk
827 @deffnx {Scheme Procedure} with-output-to-file filename thunk
828 @deffnx {Scheme Procedure} with-error-to-file filename thunk
829 @rnindex with-input-from-file
830 @rnindex with-output-to-file
831 Open @var{filename} and call @code{(@var{thunk})} with the new port
832 setup as respectively the @code{current-input-port},
833 @code{current-output-port}, or @code{current-error-port}. Return the
834 value returned by @var{thunk}. @var{filename} is opened as per
835 @code{open-input-file} or @code{open-output-file} respectively, and an
836 error is signalled if it cannot be opened.
838 When @var{thunk} returns, the port is closed and the previous setting
839 of the respective current port is restored.
841 The current port setting is managed with @code{dynamic-wind}, so the
842 previous value is restored no matter how @var{thunk} exits (eg.@: an
843 exception), and if @var{thunk} is re-entered (via a captured
844 continuation) then it's set again to the @var{FILENAME} port.
846 The port is closed when @var{thunk} returns normally, but not when
847 exited via an exception or new continuation. This ensures it's still
848 ready for use if @var{thunk} is re-entered by a captured continuation.
849 Of course the port is always garbage collected and closed in the usual
850 way when no longer referenced anywhere.
853 @deffn {Scheme Procedure} port-mode port
854 @deffnx {C Function} scm_port_mode (port)
855 Return the port modes associated with the open port @var{port}.
856 These will not necessarily be identical to the modes used when
857 the port was opened, since modes such as "append" which are
858 used only during port creation are not retained.
861 @deffn {Scheme Procedure} port-filename port
862 @deffnx {C Function} scm_port_filename (port)
863 Return the filename associated with @var{port}. This function returns
864 the strings "standard input", "standard output" and "standard error"
865 when called on the current input, output and error ports respectively.
867 @var{port} must be open, @code{port-filename} cannot be used once the
871 @deffn {Scheme Procedure} set-port-filename! port filename
872 @deffnx {C Function} scm_set_port_filename_x (port, filename)
873 Change the filename associated with @var{port}, using the current input
874 port if none is specified. Note that this does not change the port's
875 source of data, but only the value that is returned by
876 @code{port-filename} and reported in diagnostic output.
879 @deffn {Scheme Procedure} file-port? obj
880 @deffnx {C Function} scm_file_port_p (obj)
881 Determine whether @var{obj} is a port that is related to a file.
886 @subsubsection String Ports
890 The following allow string ports to be opened by analogy to R4R*
891 file port facilities:
893 @deffn {Scheme Procedure} call-with-output-string proc
894 @deffnx {C Function} scm_call_with_output_string (proc)
895 Calls the one-argument procedure @var{proc} with a newly created output
896 port. When the function returns, the string composed of the characters
897 written into the port is returned. @var{proc} should not close the port.
900 @deffn {Scheme Procedure} call-with-input-string string proc
901 @deffnx {C Function} scm_call_with_input_string (string, proc)
902 Calls the one-argument procedure @var{proc} with a newly
903 created input port from which @var{string}'s contents may be
904 read. The value yielded by the @var{proc} is returned.
907 @deffn {Scheme Procedure} with-output-to-string thunk
908 Calls the zero-argument procedure @var{thunk} with the current output
909 port set temporarily to a new string port. It returns a string
910 composed of the characters written to the current output.
913 @deffn {Scheme Procedure} with-input-from-string string thunk
914 Calls the zero-argument procedure @var{thunk} with the current input
915 port set temporarily to a string port opened on the specified
916 @var{string}. The value yielded by @var{thunk} is returned.
919 @deffn {Scheme Procedure} open-input-string str
920 @deffnx {C Function} scm_open_input_string (str)
921 Take a string and return an input port that delivers characters
922 from the string. The port can be closed by
923 @code{close-input-port}, though its storage will be reclaimed
924 by the garbage collector if it becomes inaccessible.
927 @deffn {Scheme Procedure} open-output-string
928 @deffnx {C Function} scm_open_output_string ()
929 Return an output port that will accumulate characters for
930 retrieval by @code{get-output-string}. The port can be closed
931 by the procedure @code{close-output-port}, though its storage
932 will be reclaimed by the garbage collector if it becomes
936 @deffn {Scheme Procedure} get-output-string port
937 @deffnx {C Function} scm_get_output_string (port)
938 Given an output port created by @code{open-output-string},
939 return a string consisting of the characters that have been
940 output to the port so far.
942 @code{get-output-string} must be used before closing @var{port}, once
943 closed the string cannot be obtained.
946 A string port can be used in many procedures which accept a port
947 but which are not dependent on implementation details of fports.
948 E.g., seeking and truncating will work on a string port,
949 but trying to extract the file descriptor number will fail.
953 @subsubsection Soft Ports
957 A @dfn{soft-port} is a port based on a vector of procedures capable of
958 accepting or delivering characters. It allows emulation of I/O ports.
960 @deffn {Scheme Procedure} make-soft-port pv modes
961 @deffnx {C Function} scm_make_soft_port (pv, modes)
962 Return a port capable of receiving or delivering characters as
963 specified by the @var{modes} string (@pxref{File Ports,
964 open-file}). @var{pv} must be a vector of length 5 or 6. Its
965 components are as follows:
969 procedure accepting one character for output
971 procedure accepting a string for output
973 thunk for flushing output
975 thunk for getting one character
977 thunk for closing port (not by garbage collection)
979 (if present and not @code{#f}) thunk for computing the number of
980 characters that can be read from the port without blocking.
983 For an output-only port only elements 0, 1, 2, and 4 need be
984 procedures. For an input-only port only elements 3 and 4 need
985 be procedures. Thunks 2 and 4 can instead be @code{#f} if
986 there is no useful operation for them to perform.
988 If thunk 3 returns @code{#f} or an @code{eof-object}
989 (@pxref{Input, eof-object?, ,r5rs, The Revised^5 Report on
990 Scheme}) it indicates that the port has reached end-of-file.
994 (define stdout (current-output-port))
995 (define p (make-soft-port
997 (lambda (c) (write c stdout))
998 (lambda (s) (display s stdout))
999 (lambda () (display "." stdout))
1000 (lambda () (char-upcase (read-char)))
1001 (lambda () (display "@@" stdout)))
1004 (write p p) @result{} #<input-output: soft 8081e20>
1010 @subsubsection Void Ports
1014 This kind of port causes any data to be discarded when written to, and
1015 always returns the end-of-file object when read from.
1017 @deffn {Scheme Procedure} %make-void-port mode
1018 @deffnx {C Function} scm_sys_make_void_port (mode)
1019 Create and return a new void port. A void port acts like
1020 @file{/dev/null}. The @var{mode} argument
1021 specifies the input/output modes for this port: see the
1022 documentation for @code{open-file} in @ref{File Ports}.
1026 @node I/O Extensions
1027 @subsection Using and Extending Ports in C
1030 * C Port Interface:: Using ports from C.
1031 * Port Implementation:: How to implement a new port type in C.
1035 @node C Port Interface
1036 @subsubsection C Port Interface
1037 @cindex C port interface
1038 @cindex Port, C interface
1040 This section describes how to use Scheme ports from C.
1042 @subsubheading Port basics
1045 @tindex scm_ptob_descriptor
1047 @findex SCM_PTAB_ENTRY
1050 There are two main data structures. A port type object (ptob) is of
1051 type @code{scm_ptob_descriptor}. A port instance is of type
1052 @code{scm_port}. Given an @code{SCM} variable which points to a port,
1053 the corresponding C port object can be obtained using the
1054 @code{SCM_PTAB_ENTRY} macro. The ptob can be obtained by using
1055 @code{SCM_PTOBNUM} to give an index into the @code{scm_ptobs}
1058 @subsubheading Port buffers
1060 An input port always has a read buffer and an output port always has a
1061 write buffer. However the size of these buffers is not guaranteed to be
1062 more than one byte (e.g., the @code{shortbuf} field in @code{scm_port}
1063 which is used when no other buffer is allocated). The way in which the
1064 buffers are allocated depends on the implementation of the ptob. For
1065 example in the case of an fport, buffers may be allocated with malloc
1066 when the port is created, but in the case of an strport the underlying
1067 string is used as the buffer.
1069 @subsubheading The @code{rw_random} flag
1071 Special treatment is required for ports which can be seeked at random.
1072 Before various operations, such as seeking the port or changing from
1073 input to output on a bidirectional port or vice versa, the port
1074 implementation must be given a chance to update its state. The write
1075 buffer is updated by calling the @code{flush} ptob procedure and the
1076 input buffer is updated by calling the @code{end_input} ptob procedure.
1077 In the case of an fport, @code{flush} causes buffered output to be
1078 written to the file descriptor, while @code{end_input} causes the
1079 descriptor position to be adjusted to account for buffered input which
1082 The special treatment must be performed if the @code{rw_random} flag in
1083 the port is non-zero.
1085 @subsubheading The @code{rw_active} variable
1087 The @code{rw_active} variable in the port is only used if
1088 @code{rw_random} is set. It's defined as an enum with the following
1093 the read buffer may have unread data.
1095 @item SCM_PORT_WRITE
1096 the write buffer may have unwritten data.
1098 @item SCM_PORT_NEITHER
1099 neither the write nor the read buffer has data.
1102 @subsubheading Reading from a port.
1104 To read from a port, it's possible to either call existing libguile
1105 procedures such as @code{scm_getc} and @code{scm_read_line} or to read
1106 data from the read buffer directly. Reading from the buffer involves
1107 the following steps:
1111 Flush output on the port, if @code{rw_active} is @code{SCM_PORT_WRITE}.
1114 Fill the read buffer, if it's empty, using @code{scm_fill_input}.
1116 @item Read the data from the buffer and update the read position in
1117 the buffer. Steps 2) and 3) may be repeated as many times as required.
1119 @item Set rw_active to @code{SCM_PORT_READ} if @code{rw_random} is set.
1121 @item update the port's line and column counts.
1124 @subsubheading Writing to a port.
1126 To write data to a port, calling @code{scm_lfwrite} should be sufficient for
1127 most purposes. This takes care of the following steps:
1131 End input on the port, if @code{rw_active} is @code{SCM_PORT_READ}.
1134 Pass the data to the ptob implementation using the @code{write} ptob
1135 procedure. The advantage of using the ptob @code{write} instead of
1136 manipulating the write buffer directly is that it allows the data to be
1137 written in one operation even if the port is using the single-byte
1141 Set @code{rw_active} to @code{SCM_PORT_WRITE} if @code{rw_random}
1146 @node Port Implementation
1147 @subsubsection Port Implementation
1148 @cindex Port implemenation
1150 This section describes how to implement a new port type in C.
1152 As described in the previous section, a port type object (ptob) is
1153 a structure of type @code{scm_ptob_descriptor}. A ptob is created by
1154 calling @code{scm_make_port_type}.
1156 @deftypefun scm_t_bits scm_make_port_type (char *name, int (*fill_input) (SCM port), void (*write) (SCM port, const void *data, size_t size))
1157 Return a new port type object. The @var{name}, @var{fill_input} and
1158 @var{write} parameters are initial values for those port type fields,
1159 as described below. The other fields are initialized with default
1160 values and can be changed later.
1163 All of the elements of the ptob, apart from @code{name}, are procedures
1164 which collectively implement the port behaviour. Creating a new port
1165 type mostly involves writing these procedures.
1169 A pointer to a NUL terminated string: the name of the port type. This
1170 is the only element of @code{scm_ptob_descriptor} which is not
1171 a procedure. Set via the first argument to @code{scm_make_port_type}.
1174 Called during garbage collection to mark any SCM objects that a port
1175 object may contain. It doesn't need to be set unless the port has
1176 @code{SCM} components. Set using
1178 @deftypefun void scm_set_port_mark (scm_t_bits tc, SCM (*mark) (SCM port))
1182 Called when the port is collected during gc. It
1183 should free any resources used by the port.
1186 @deftypefun void scm_set_port_free (scm_t_bits tc, size_t (*free) (SCM port))
1190 Called when @code{write} is called on the port object, to print a
1191 port description. E.g., for an fport it may produce something like:
1192 @code{#<input: /etc/passwd 3>}. Set using
1194 @deftypefun void scm_set_port_print (scm_t_bits tc, int (*print) (SCM port, SCM dest_port, scm_print_state *pstate))
1195 The first argument @var{port} is the object being printed, the second
1196 argument @var{dest_port} is where its description should go.
1200 Not used at present. Set using
1202 @deftypefun void scm_set_port_equalp (scm_t_bits tc, SCM (*equalp) (SCM, SCM))
1206 Called when the port is closed, unless it was collected during gc. It
1207 should free any resources used by the port.
1210 @deftypefun void scm_set_port_close (scm_t_bits tc, int (*close) (SCM port))
1214 Accept data which is to be written using the port. The port implementation
1215 may choose to buffer the data instead of processing it directly.
1216 Set via the third argument to @code{scm_make_port_type}.
1219 Complete the processing of buffered output data. Reset the value of
1220 @code{rw_active} to @code{SCM_PORT_NEITHER}.
1223 @deftypefun void scm_set_port_flush (scm_t_bits tc, void (*flush) (SCM port))
1227 Perform any synchronization required when switching from input to output
1228 on the port. Reset the value of @code{rw_active} to @code{SCM_PORT_NEITHER}.
1231 @deftypefun void scm_set_port_end_input (scm_t_bits tc, void (*end_input) (SCM port, int offset))
1235 Read new data into the read buffer and return the first character. It
1236 can be assumed that the read buffer is empty when this procedure is called.
1237 Set via the second argument to @code{scm_make_port_type}.
1240 Return a lower bound on the number of bytes that could be read from the
1241 port without blocking. It can be assumed that the current state of
1242 @code{rw_active} is @code{SCM_PORT_NEITHER}.
1245 @deftypefun void scm_set_port_input_waiting (scm_t_bits tc, int (*input_waiting) (SCM port))
1249 Set the current position of the port. The procedure can not make
1250 any assumptions about the value of @code{rw_active} when it's
1251 called. It can reset the buffers first if desired by using something
1255 if (pt->rw_active == SCM_PORT_READ)
1256 scm_end_input (port);
1257 else if (pt->rw_active == SCM_PORT_WRITE)
1261 However note that this will have the side effect of discarding any data
1262 in the unread-char buffer, in addition to any side effects from the
1263 @code{end_input} and @code{flush} ptob procedures. This is undesirable
1264 when seek is called to measure the current position of the port, i.e.,
1265 @code{(seek p 0 SEEK_CUR)}. The libguile fport and string port
1266 implementations take care to avoid this problem.
1268 The procedure is set using
1270 @deftypefun void scm_set_port_seek (scm_t_bits tc, off_t (*seek) (SCM port, off_t offset, int whence))
1274 Truncate the port data to be specified length. It can be assumed that the
1275 current state of @code{rw_active} is @code{SCM_PORT_NEITHER}.
1278 @deftypefun void scm_set_port_truncate (scm_t_bits tc, void (*truncate) (SCM port, off_t length))
1285 @c TeX-master: "guile.texi"