Add `scm_t_off' type so that `scm_t_port' has a fixed layout.
[bpt/guile.git] / doc / ref / api-io.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2009
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @page
8 @node Input and Output
9 @section Input and Output
10
11 @menu
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 * R6RS I/O Ports:: The R6RS port API.
22 * I/O Extensions:: Using and extending ports in C.
23 @end menu
24
25
26 @node Ports
27 @subsection Ports
28 @cindex Port
29
30 Sequential input/output in Scheme is represented by operations on a
31 @dfn{port}. This chapter explains the operations that Guile provides
32 for working with ports.
33
34 Ports are created by opening, for instance @code{open-file} for a file
35 (@pxref{File Ports}). Characters can be read from an input port and
36 written to an output port, or both on an input/output port. A port
37 can be closed (@pxref{Closing}) when no longer required, after which
38 any attempt to read or write is an error.
39
40 The formal definition of a port is very generic: an input port is
41 simply ``an object which can deliver characters on demand,'' and an
42 output port is ``an object which can accept characters.'' Because
43 this definition is so loose, it is easy to write functions that
44 simulate ports in software. @dfn{Soft ports} and @dfn{string ports}
45 are two interesting and powerful examples of this technique.
46 (@pxref{Soft Ports}, and @ref{String Ports}.)
47
48 Ports are garbage collected in the usual way (@pxref{Memory
49 Management}), and will be closed at that time if not already closed.
50 In this case any errors occuring in the close will not be reported.
51 Usually a program will want to explicitly close so as to be sure all
52 its operations have been successful. Of course if a program has
53 abandoned something due to an error or other condition then closing
54 problems are probably not of interest.
55
56 It is strongly recommended that file ports be closed explicitly when
57 no longer required. Most systems have limits on how many files can be
58 open, both on a per-process and a system-wide basis. A program that
59 uses many files should take care not to hit those limits. The same
60 applies to similar system resources such as pipes and sockets.
61
62 Note that automatic garbage collection is triggered only by memory
63 consumption, not by file or other resource usage, so a program cannot
64 rely on that to keep it away from system limits. An explicit call to
65 @code{gc} can of course be relied on to pick up unreferenced ports.
66 If program flow makes it hard to be certain when to close then this
67 may be an acceptable way to control resource usage.
68
69 All file access uses the ``LFS'' large file support functions when
70 available, so files bigger than 2 Gbytes (@math{2^31} bytes) can be
71 read and written on a 32-bit system.
72
73 @rnindex input-port?
74 @deffn {Scheme Procedure} input-port? x
75 @deffnx {C Function} scm_input_port_p (x)
76 Return @code{#t} if @var{x} is an input port, otherwise return
77 @code{#f}. Any object satisfying this predicate also satisfies
78 @code{port?}.
79 @end deffn
80
81 @rnindex output-port?
82 @deffn {Scheme Procedure} output-port? x
83 @deffnx {C Function} scm_output_port_p (x)
84 Return @code{#t} if @var{x} is an output port, otherwise return
85 @code{#f}. Any object satisfying this predicate also satisfies
86 @code{port?}.
87 @end deffn
88
89 @deffn {Scheme Procedure} port? x
90 @deffnx {C Function} scm_port_p (x)
91 Return a boolean indicating whether @var{x} is a port.
92 Equivalent to @code{(or (input-port? @var{x}) (output-port?
93 @var{x}))}.
94 @end deffn
95
96
97 @node Reading
98 @subsection Reading
99 @cindex Reading
100
101 [Generic procedures for reading from ports.]
102
103 @rnindex eof-object?
104 @cindex End of file object
105 @deffn {Scheme Procedure} eof-object? x
106 @deffnx {C Function} scm_eof_object_p (x)
107 Return @code{#t} if @var{x} is an end-of-file object; otherwise
108 return @code{#f}.
109 @end deffn
110
111 @rnindex char-ready?
112 @deffn {Scheme Procedure} char-ready? [port]
113 @deffnx {C Function} scm_char_ready_p (port)
114 Return @code{#t} if a character is ready on input @var{port}
115 and return @code{#f} otherwise. If @code{char-ready?} returns
116 @code{#t} then the next @code{read-char} operation on
117 @var{port} is guaranteed not to hang. If @var{port} is a file
118 port at end of file then @code{char-ready?} returns @code{#t}.
119
120 @code{char-ready?} exists to make it possible for a
121 program to accept characters from interactive ports without
122 getting stuck waiting for input. Any input editors associated
123 with such ports must make sure that characters whose existence
124 has been asserted by @code{char-ready?} cannot be rubbed out.
125 If @code{char-ready?} were to return @code{#f} at end of file,
126 a port at end of file would be indistinguishable from an
127 interactive port that has no ready characters.
128 @end deffn
129
130 @rnindex read-char
131 @deffn {Scheme Procedure} read-char [port]
132 @deffnx {C Function} scm_read_char (port)
133 Return the next character available from @var{port}, updating
134 @var{port} to point to the following character. If no more
135 characters are available, the end-of-file object is returned.
136 @end deffn
137
138 @deftypefn {C Function} size_t scm_c_read (SCM port, void *buffer, size_t size)
139 Read up to @var{size} bytes from @var{port} and store them in
140 @var{buffer}. The return value is the number of bytes actually read,
141 which can be less than @var{size} if end-of-file has been reached.
142
143 Note that this function does not update @code{port-line} and
144 @code{port-column} below.
145 @end deftypefn
146
147 @rnindex peek-char
148 @deffn {Scheme Procedure} peek-char [port]
149 @deffnx {C Function} scm_peek_char (port)
150 Return the next character available from @var{port},
151 @emph{without} updating @var{port} to point to the following
152 character. If no more characters are available, the
153 end-of-file object is returned.
154
155 The value returned by
156 a call to @code{peek-char} is the same as the value that would
157 have been returned by a call to @code{read-char} on the same
158 port. The only difference is that the very next call to
159 @code{read-char} or @code{peek-char} on that @var{port} will
160 return the value returned by the preceding call to
161 @code{peek-char}. In particular, a call to @code{peek-char} on
162 an interactive port will hang waiting for input whenever a call
163 to @code{read-char} would have hung.
164 @end deffn
165
166 @deffn {Scheme Procedure} unread-char cobj [port]
167 @deffnx {C Function} scm_unread_char (cobj, port)
168 Place @var{char} in @var{port} so that it will be read by the
169 next read operation. If called multiple times, the unread characters
170 will be read again in last-in first-out order. If @var{port} is
171 not supplied, the current input port is used.
172 @end deffn
173
174 @deffn {Scheme Procedure} unread-string str port
175 @deffnx {C Function} scm_unread_string (str, port)
176 Place the string @var{str} in @var{port} so that its characters will
177 be read from left-to-right as the next characters from @var{port}
178 during subsequent read operations. If called multiple times, the
179 unread characters will be read again in last-in first-out order. If
180 @var{port} is not supplied, the @code{current-input-port} is used.
181 @end deffn
182
183 @deffn {Scheme Procedure} drain-input port
184 @deffnx {C Function} scm_drain_input (port)
185 This procedure clears a port's input buffers, similar
186 to the way that force-output clears the output buffer. The
187 contents of the buffers are returned as a single string, e.g.,
188
189 @lisp
190 (define p (open-input-file ...))
191 (drain-input p) => empty string, nothing buffered yet.
192 (unread-char (read-char p) p)
193 (drain-input p) => initial chars from p, up to the buffer size.
194 @end lisp
195
196 Draining the buffers may be useful for cleanly finishing
197 buffered I/O so that the file descriptor can be used directly
198 for further input.
199 @end deffn
200
201 @deffn {Scheme Procedure} port-column port
202 @deffnx {Scheme Procedure} port-line port
203 @deffnx {C Function} scm_port_column (port)
204 @deffnx {C Function} scm_port_line (port)
205 Return the current column number or line number of @var{port}.
206 If the number is
207 unknown, the result is #f. Otherwise, the result is a 0-origin integer
208 - i.e.@: the first character of the first line is line 0, column 0.
209 (However, when you display a file position, for example in an error
210 message, we recommend you add 1 to get 1-origin integers. This is
211 because lines and column numbers traditionally start with 1, and that is
212 what non-programmers will find most natural.)
213 @end deffn
214
215 @deffn {Scheme Procedure} set-port-column! port column
216 @deffnx {Scheme Procedure} set-port-line! port line
217 @deffnx {C Function} scm_set_port_column_x (port, column)
218 @deffnx {C Function} scm_set_port_line_x (port, line)
219 Set the current column or line number of @var{port}.
220 @end deffn
221
222 @node Writing
223 @subsection Writing
224 @cindex Writing
225
226 [Generic procedures for writing to ports.]
227
228 @deffn {Scheme Procedure} get-print-state port
229 @deffnx {C Function} scm_get_print_state (port)
230 Return the print state of the port @var{port}. If @var{port}
231 has no associated print state, @code{#f} is returned.
232 @end deffn
233
234 @rnindex write
235 @deffn {Scheme Procedure} write obj [port]
236 Send a representation of @var{obj} to @var{port} or to the current
237 output port if not given.
238
239 The output is designed to be machine readable, and can be read back
240 with @code{read} (@pxref{Reading}). Strings are printed in
241 doublequotes, with escapes if necessary, and characters are printed in
242 @samp{#\} notation.
243 @end deffn
244
245 @rnindex display
246 @deffn {Scheme Procedure} display obj [port]
247 Send a representation of @var{obj} to @var{port} or to the current
248 output port if not given.
249
250 The output is designed for human readability, it differs from
251 @code{write} in that strings are printed without doublequotes and
252 escapes, and characters are printed as per @code{write-char}, not in
253 @samp{#\} form.
254 @end deffn
255
256 @rnindex newline
257 @deffn {Scheme Procedure} newline [port]
258 @deffnx {C Function} scm_newline (port)
259 Send a newline to @var{port}.
260 If @var{port} is omitted, send to the current output port.
261 @end deffn
262
263 @deffn {Scheme Procedure} port-with-print-state port [pstate]
264 @deffnx {C Function} scm_port_with_print_state (port, pstate)
265 Create a new port which behaves like @var{port}, but with an
266 included print state @var{pstate}. @var{pstate} is optional.
267 If @var{pstate} isn't supplied and @var{port} already has
268 a print state, the old print state is reused.
269 @end deffn
270
271 @deffn {Scheme Procedure} print-options-interface [setting]
272 @deffnx {C Function} scm_print_options (setting)
273 Option interface for the print options. Instead of using
274 this procedure directly, use the procedures
275 @code{print-enable}, @code{print-disable}, @code{print-set!}
276 and @code{print-options}.
277 @end deffn
278
279 @deffn {Scheme Procedure} simple-format destination message . args
280 @deffnx {C Function} scm_simple_format (destination, message, args)
281 Write @var{message} to @var{destination}, defaulting to
282 the current output port.
283 @var{message} can contain @code{~A} (was @code{%s}) and
284 @code{~S} (was @code{%S}) escapes. When printed,
285 the escapes are replaced with corresponding members of
286 @var{ARGS}:
287 @code{~A} formats using @code{display} and @code{~S} formats
288 using @code{write}.
289 If @var{destination} is @code{#t}, then use the current output
290 port, if @var{destination} is @code{#f}, then return a string
291 containing the formatted text. Does not add a trailing newline.
292 @end deffn
293
294 @rnindex write-char
295 @deffn {Scheme Procedure} write-char chr [port]
296 @deffnx {C Function} scm_write_char (chr, port)
297 Send character @var{chr} to @var{port}.
298 @end deffn
299
300 @deftypefn {C Function} void scm_c_write (SCM port, const void *buffer, size_t size)
301 Write @var{size} bytes at @var{buffer} to @var{port}.
302
303 Note that this function does not update @code{port-line} and
304 @code{port-column} (@pxref{Reading}).
305 @end deftypefn
306
307 @findex fflush
308 @deffn {Scheme Procedure} force-output [port]
309 @deffnx {C Function} scm_force_output (port)
310 Flush the specified output port, or the current output port if @var{port}
311 is omitted. The current output buffer contents are passed to the
312 underlying port implementation (e.g., in the case of fports, the
313 data will be written to the file and the output buffer will be cleared.)
314 It has no effect on an unbuffered port.
315
316 The return value is unspecified.
317 @end deffn
318
319 @deffn {Scheme Procedure} flush-all-ports
320 @deffnx {C Function} scm_flush_all_ports ()
321 Equivalent to calling @code{force-output} on
322 all open output ports. The return value is unspecified.
323 @end deffn
324
325
326 @node Closing
327 @subsection Closing
328 @cindex Closing ports
329 @cindex Port, close
330
331 @deffn {Scheme Procedure} close-port port
332 @deffnx {C Function} scm_close_port (port)
333 Close the specified port object. Return @code{#t} if it
334 successfully closes a port or @code{#f} if it was already
335 closed. An exception may be raised if an error occurs, for
336 example when flushing buffered output. See also @ref{Ports and
337 File Descriptors, close}, for a procedure which can close file
338 descriptors.
339 @end deffn
340
341 @deffn {Scheme Procedure} close-input-port port
342 @deffnx {Scheme Procedure} close-output-port port
343 @deffnx {C Function} scm_close_input_port (port)
344 @deffnx {C Function} scm_close_output_port (port)
345 @rnindex close-input-port
346 @rnindex close-output-port
347 Close the specified input or output @var{port}. An exception may be
348 raised if an error occurs while closing. If @var{port} is already
349 closed, nothing is done. The return value is unspecified.
350
351 See also @ref{Ports and File Descriptors, close}, for a procedure
352 which can close file descriptors.
353 @end deffn
354
355 @deffn {Scheme Procedure} port-closed? port
356 @deffnx {C Function} scm_port_closed_p (port)
357 Return @code{#t} if @var{port} is closed or @code{#f} if it is
358 open.
359 @end deffn
360
361
362 @node Random Access
363 @subsection Random Access
364 @cindex Random access, ports
365 @cindex Port, random access
366
367 @deffn {Scheme Procedure} seek fd_port offset whence
368 @deffnx {C Function} scm_seek (fd_port, offset, whence)
369 Sets the current position of @var{fd/port} to the integer
370 @var{offset}, which is interpreted according to the value of
371 @var{whence}.
372
373 One of the following variables should be supplied for
374 @var{whence}:
375 @defvar SEEK_SET
376 Seek from the beginning of the file.
377 @end defvar
378 @defvar SEEK_CUR
379 Seek from the current position.
380 @end defvar
381 @defvar SEEK_END
382 Seek from the end of the file.
383 @end defvar
384 If @var{fd/port} is a file descriptor, the underlying system
385 call is @code{lseek}. @var{port} may be a string port.
386
387 The value returned is the new position in the file. This means
388 that the current position of a port can be obtained using:
389 @lisp
390 (seek port 0 SEEK_CUR)
391 @end lisp
392 @end deffn
393
394 @deffn {Scheme Procedure} ftell fd_port
395 @deffnx {C Function} scm_ftell (fd_port)
396 Return an integer representing the current position of
397 @var{fd/port}, measured from the beginning. Equivalent to:
398
399 @lisp
400 (seek port 0 SEEK_CUR)
401 @end lisp
402 @end deffn
403
404 @findex truncate
405 @findex ftruncate
406 @deffn {Scheme Procedure} truncate-file file [length]
407 @deffnx {C Function} scm_truncate_file (file, length)
408 Truncate @var{file} to @var{length} bytes. @var{file} can be a
409 filename string, a port object, or an integer file descriptor. The
410 return value is unspecified.
411
412 For a port or file descriptor @var{length} can be omitted, in which
413 case the file is truncated at the current position (per @code{ftell}
414 above).
415
416 On most systems a file can be extended by giving a length greater than
417 the current size, but this is not mandatory in the POSIX standard.
418 @end deffn
419
420 @node Line/Delimited
421 @subsection Line Oriented and Delimited Text
422 @cindex Line input/output
423 @cindex Port, line input/output
424
425 The delimited-I/O module can be accessed with:
426
427 @smalllisp
428 (use-modules (ice-9 rdelim))
429 @end smalllisp
430
431 It can be used to read or write lines of text, or read text delimited by
432 a specified set of characters. It's similar to the @code{(scsh rdelim)}
433 module from guile-scsh, but does not use multiple values or character
434 sets and has an extra procedure @code{write-line}.
435
436 @c begin (scm-doc-string "rdelim.scm" "read-line")
437 @deffn {Scheme Procedure} read-line [port] [handle-delim]
438 Return a line of text from @var{port} if specified, otherwise from the
439 value returned by @code{(current-input-port)}. Under Unix, a line of text
440 is terminated by the first end-of-line character or by end-of-file.
441
442 If @var{handle-delim} is specified, it should be one of the following
443 symbols:
444 @table @code
445 @item trim
446 Discard the terminating delimiter. This is the default, but it will
447 be impossible to tell whether the read terminated with a delimiter or
448 end-of-file.
449 @item concat
450 Append the terminating delimiter (if any) to the returned string.
451 @item peek
452 Push the terminating delimiter (if any) back on to the port.
453 @item split
454 Return a pair containing the string read from the port and the
455 terminating delimiter or end-of-file object.
456 @end table
457 @end deffn
458
459 @c begin (scm-doc-string "rdelim.scm" "read-line!")
460 @deffn {Scheme Procedure} read-line! buf [port]
461 Read a line of text into the supplied string @var{buf} and return the
462 number of characters added to @var{buf}. If @var{buf} is filled, then
463 @code{#f} is returned.
464 Read from @var{port} if
465 specified, otherwise from the value returned by @code{(current-input-port)}.
466 @end deffn
467
468 @c begin (scm-doc-string "rdelim.scm" "read-delimited")
469 @deffn {Scheme Procedure} read-delimited delims [port] [handle-delim]
470 Read text until one of the characters in the string @var{delims} is found
471 or end-of-file is reached. Read from @var{port} if supplied, otherwise
472 from the value returned by @code{(current-input-port)}.
473 @var{handle-delim} takes the same values as described for @code{read-line}.
474 @end deffn
475
476 @c begin (scm-doc-string "rdelim.scm" "read-delimited!")
477 @deffn {Scheme Procedure} read-delimited! delims buf [port] [handle-delim] [start] [end]
478 Read text into the supplied string @var{buf} and return the number of
479 characters added to @var{buf} (subject to @var{handle-delim}, which takes
480 the same values specified for @code{read-line}. If @var{buf} is filled,
481 @code{#f} is returned for both the number of characters read and the
482 delimiter. Also terminates if one of the characters in the string
483 @var{delims} is found
484 or end-of-file is reached. Read from @var{port} if supplied, otherwise
485 from the value returned by @code{(current-input-port)}.
486 @end deffn
487
488 @deffn {Scheme Procedure} write-line obj [port]
489 @deffnx {C Function} scm_write_line (obj, port)
490 Display @var{obj} and a newline character to @var{port}. If
491 @var{port} is not specified, @code{(current-output-port)} is
492 used. This function is equivalent to:
493 @lisp
494 (display obj [port])
495 (newline [port])
496 @end lisp
497 @end deffn
498
499 Some of the abovementioned I/O functions rely on the following C
500 primitives. These will mainly be of interest to people hacking Guile
501 internals.
502
503 @deffn {Scheme Procedure} %read-delimited! delims str gobble [port [start [end]]]
504 @deffnx {C Function} scm_read_delimited_x (delims, str, gobble, port, start, end)
505 Read characters from @var{port} into @var{str} until one of the
506 characters in the @var{delims} string is encountered. If
507 @var{gobble} is true, discard the delimiter character;
508 otherwise, leave it in the input stream for the next read. If
509 @var{port} is not specified, use the value of
510 @code{(current-input-port)}. If @var{start} or @var{end} are
511 specified, store data only into the substring of @var{str}
512 bounded by @var{start} and @var{end} (which default to the
513 beginning and end of the string, respectively).
514
515 Return a pair consisting of the delimiter that terminated the
516 string and the number of characters read. If reading stopped
517 at the end of file, the delimiter returned is the
518 @var{eof-object}; if the string was filled without encountering
519 a delimiter, this value is @code{#f}.
520 @end deffn
521
522 @deffn {Scheme Procedure} %read-line [port]
523 @deffnx {C Function} scm_read_line (port)
524 Read a newline-terminated line from @var{port}, allocating storage as
525 necessary. The newline terminator (if any) is removed from the string,
526 and a pair consisting of the line and its delimiter is returned. The
527 delimiter may be either a newline or the @var{eof-object}; if
528 @code{%read-line} is called at the end of file, it returns the pair
529 @code{(#<eof> . #<eof>)}.
530 @end deffn
531
532 @node Block Reading and Writing
533 @subsection Block reading and writing
534 @cindex Block read/write
535 @cindex Port, block read/write
536
537 The Block-string-I/O module can be accessed with:
538
539 @smalllisp
540 (use-modules (ice-9 rw))
541 @end smalllisp
542
543 It currently contains procedures that help to implement the
544 @code{(scsh rw)} module in guile-scsh.
545
546 @deffn {Scheme Procedure} read-string!/partial str [port_or_fdes [start [end]]]
547 @deffnx {C Function} scm_read_string_x_partial (str, port_or_fdes, start, end)
548 Read characters from a port or file descriptor into a
549 string @var{str}. A port must have an underlying file
550 descriptor --- a so-called fport. This procedure is
551 scsh-compatible and can efficiently read large strings.
552 It will:
553
554 @itemize
555 @item
556 attempt to fill the entire string, unless the @var{start}
557 and/or @var{end} arguments are supplied. i.e., @var{start}
558 defaults to 0 and @var{end} defaults to
559 @code{(string-length str)}
560 @item
561 use the current input port if @var{port_or_fdes} is not
562 supplied.
563 @item
564 return fewer than the requested number of characters in some
565 cases, e.g., on end of file, if interrupted by a signal, or if
566 not all the characters are immediately available.
567 @item
568 wait indefinitely for some input if no characters are
569 currently available,
570 unless the port is in non-blocking mode.
571 @item
572 read characters from the port's input buffers if available,
573 instead from the underlying file descriptor.
574 @item
575 return @code{#f} if end-of-file is encountered before reading
576 any characters, otherwise return the number of characters
577 read.
578 @item
579 return 0 if the port is in non-blocking mode and no characters
580 are immediately available.
581 @item
582 return 0 if the request is for 0 bytes, with no
583 end-of-file check.
584 @end itemize
585 @end deffn
586
587 @deffn {Scheme Procedure} write-string/partial str [port_or_fdes [start [end]]]
588 @deffnx {C Function} scm_write_string_partial (str, port_or_fdes, start, end)
589 Write characters from a string @var{str} to a port or file
590 descriptor. A port must have an underlying file descriptor
591 --- a so-called fport. This procedure is
592 scsh-compatible and can efficiently write large strings.
593 It will:
594
595 @itemize
596 @item
597 attempt to write the entire string, unless the @var{start}
598 and/or @var{end} arguments are supplied. i.e., @var{start}
599 defaults to 0 and @var{end} defaults to
600 @code{(string-length str)}
601 @item
602 use the current output port if @var{port_of_fdes} is not
603 supplied.
604 @item
605 in the case of a buffered port, store the characters in the
606 port's output buffer, if all will fit. If they will not fit
607 then any existing buffered characters will be flushed
608 before attempting
609 to write the new characters directly to the underlying file
610 descriptor. If the port is in non-blocking mode and
611 buffered characters can not be flushed immediately, then an
612 @code{EAGAIN} system-error exception will be raised (Note:
613 scsh does not support the use of non-blocking buffered ports.)
614 @item
615 write fewer than the requested number of
616 characters in some cases, e.g., if interrupted by a signal or
617 if not all of the output can be accepted immediately.
618 @item
619 wait indefinitely for at least one character
620 from @var{str} to be accepted by the port, unless the port is
621 in non-blocking mode.
622 @item
623 return the number of characters accepted by the port.
624 @item
625 return 0 if the port is in non-blocking mode and can not accept
626 at least one character from @var{str} immediately
627 @item
628 return 0 immediately if the request size is 0 bytes.
629 @end itemize
630 @end deffn
631
632 @node Default Ports
633 @subsection Default Ports for Input, Output and Errors
634 @cindex Default ports
635 @cindex Port, default
636
637 @rnindex current-input-port
638 @deffn {Scheme Procedure} current-input-port
639 @deffnx {C Function} scm_current_input_port ()
640 @cindex standard input
641 Return the current input port. This is the default port used
642 by many input procedures.
643
644 Initially this is the @dfn{standard input} in Unix and C terminology.
645 When the standard input is a tty the port is unbuffered, otherwise
646 it's fully buffered.
647
648 Unbuffered input is good if an application runs an interactive
649 subprocess, since any type-ahead input won't go into Guile's buffer
650 and be unavailable to the subprocess.
651
652 Note that Guile buffering is completely separate from the tty ``line
653 discipline''. In the usual cooked mode on a tty Guile only sees a
654 line of input once the user presses @key{Return}.
655 @end deffn
656
657 @rnindex current-output-port
658 @deffn {Scheme Procedure} current-output-port
659 @deffnx {C Function} scm_current_output_port ()
660 @cindex standard output
661 Return the current output port. This is the default port used
662 by many output procedures.
663
664 Initially this is the @dfn{standard output} in Unix and C terminology.
665 When the standard output is a tty this port is unbuffered, otherwise
666 it's fully buffered.
667
668 Unbuffered output to a tty is good for ensuring progress output or a
669 prompt is seen. But an application which always prints whole lines
670 could change to line buffered, or an application with a lot of output
671 could go fully buffered and perhaps make explicit @code{force-output}
672 calls (@pxref{Writing}) at selected points.
673 @end deffn
674
675 @deffn {Scheme Procedure} current-error-port
676 @deffnx {C Function} scm_current_error_port ()
677 @cindex standard error output
678 Return the port to which errors and warnings should be sent.
679
680 Initially this is the @dfn{standard error} in Unix and C terminology.
681 When the standard error is a tty this port is unbuffered, otherwise
682 it's fully buffered.
683 @end deffn
684
685 @deffn {Scheme Procedure} set-current-input-port port
686 @deffnx {Scheme Procedure} set-current-output-port port
687 @deffnx {Scheme Procedure} set-current-error-port port
688 @deffnx {C Function} scm_set_current_input_port (port)
689 @deffnx {C Function} scm_set_current_output_port (port)
690 @deffnx {C Function} scm_set_current_error_port (port)
691 Change the ports returned by @code{current-input-port},
692 @code{current-output-port} and @code{current-error-port}, respectively,
693 so that they use the supplied @var{port} for input or output.
694 @end deffn
695
696 @deftypefn {C Function} void scm_dynwind_current_input_port (SCM port)
697 @deftypefnx {C Function} void scm_dynwind_current_output_port (SCM port)
698 @deftypefnx {C Function} void scm_dynwind_current_error_port (SCM port)
699 These functions must be used inside a pair of calls to
700 @code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
701 Wind}). During the dynwind context, the indicated port is set to
702 @var{port}.
703
704 More precisely, the current port is swapped with a `backup' value
705 whenever the dynwind context is entered or left. The backup value is
706 initialized with the @var{port} argument.
707 @end deftypefn
708
709 @node Port Types
710 @subsection Types of Port
711 @cindex Types of ports
712 @cindex Port, types
713
714 [Types of port; how to make them.]
715
716 @menu
717 * File Ports:: Ports on an operating system file.
718 * String Ports:: Ports on a Scheme string.
719 * Soft Ports:: Ports on arbitrary Scheme procedures.
720 * Void Ports:: Ports on nothing at all.
721 @end menu
722
723
724 @node File Ports
725 @subsubsection File Ports
726 @cindex File port
727 @cindex Port, file
728
729 The following procedures are used to open file ports.
730 See also @ref{Ports and File Descriptors, open}, for an interface
731 to the Unix @code{open} system call.
732
733 Most systems have limits on how many files can be open, so it's
734 strongly recommended that file ports be closed explicitly when no
735 longer required (@pxref{Ports}).
736
737 @deffn {Scheme Procedure} open-file filename mode
738 @deffnx {C Function} scm_open_file (filename, mode)
739 Open the file whose name is @var{filename}, and return a port
740 representing that file. The attributes of the port are
741 determined by the @var{mode} string. The way in which this is
742 interpreted is similar to C stdio. The first character must be
743 one of the following:
744
745 @table @samp
746 @item r
747 Open an existing file for input.
748 @item w
749 Open a file for output, creating it if it doesn't already exist
750 or removing its contents if it does.
751 @item a
752 Open a file for output, creating it if it doesn't already
753 exist. All writes to the port will go to the end of the file.
754 The "append mode" can be turned off while the port is in use
755 @pxref{Ports and File Descriptors, fcntl}
756 @end table
757
758 The following additional characters can be appended:
759
760 @table @samp
761 @item +
762 Open the port for both input and output. E.g., @code{r+}: open
763 an existing file for both input and output.
764 @item 0
765 Create an "unbuffered" port. In this case input and output
766 operations are passed directly to the underlying port
767 implementation without additional buffering. This is likely to
768 slow down I/O operations. The buffering mode can be changed
769 while a port is in use @pxref{Ports and File Descriptors,
770 setvbuf}
771 @item l
772 Add line-buffering to the port. The port output buffer will be
773 automatically flushed whenever a newline character is written.
774 @item b
775 Use binary mode. On DOS systems the default text mode converts CR+LF
776 in the file to newline for the program, whereas binary mode reads and
777 writes all bytes unchanged. On Unix-like systems there is no such
778 distinction, text files already contain just newlines and no
779 conversion is ever made. The @code{b} flag is accepted on all
780 systems, but has no effect on Unix-like systems.
781
782 (For reference, Guile leaves text versus binary up to the C library,
783 @code{b} here just adds @code{O_BINARY} to the underlying @code{open}
784 call, when that flag is available.)
785 @end table
786
787 If a file cannot be opened with the access
788 requested, @code{open-file} throws an exception.
789
790 In theory we could create read/write ports which were buffered
791 in one direction only. However this isn't included in the
792 current interfaces.
793 @end deffn
794
795 @rnindex open-input-file
796 @deffn {Scheme Procedure} open-input-file filename
797 Open @var{filename} for input. Equivalent to
798 @smalllisp
799 (open-file @var{filename} "r")
800 @end smalllisp
801 @end deffn
802
803 @rnindex open-output-file
804 @deffn {Scheme Procedure} open-output-file filename
805 Open @var{filename} for output. Equivalent to
806 @smalllisp
807 (open-file @var{filename} "w")
808 @end smalllisp
809 @end deffn
810
811 @deffn {Scheme Procedure} call-with-input-file filename proc
812 @deffnx {Scheme Procedure} call-with-output-file filename proc
813 @rnindex call-with-input-file
814 @rnindex call-with-output-file
815 Open @var{filename} for input or output, and call @code{(@var{proc}
816 port)} with the resulting port. Return the value returned by
817 @var{proc}. @var{filename} is opened as per @code{open-input-file} or
818 @code{open-output-file} respectively, and an error is signalled if it
819 cannot be opened.
820
821 When @var{proc} returns, the port is closed. If @var{proc} does not
822 return (eg.@: if it throws an error), then the port might not be
823 closed automatically, though it will be garbage collected in the usual
824 way if not otherwise referenced.
825 @end deffn
826
827 @deffn {Scheme Procedure} with-input-from-file filename thunk
828 @deffnx {Scheme Procedure} with-output-to-file filename thunk
829 @deffnx {Scheme Procedure} with-error-to-file filename thunk
830 @rnindex with-input-from-file
831 @rnindex with-output-to-file
832 Open @var{filename} and call @code{(@var{thunk})} with the new port
833 setup as respectively the @code{current-input-port},
834 @code{current-output-port}, or @code{current-error-port}. Return the
835 value returned by @var{thunk}. @var{filename} is opened as per
836 @code{open-input-file} or @code{open-output-file} respectively, and an
837 error is signalled if it cannot be opened.
838
839 When @var{thunk} returns, the port is closed and the previous setting
840 of the respective current port is restored.
841
842 The current port setting is managed with @code{dynamic-wind}, so the
843 previous value is restored no matter how @var{thunk} exits (eg.@: an
844 exception), and if @var{thunk} is re-entered (via a captured
845 continuation) then it's set again to the @var{FILENAME} port.
846
847 The port is closed when @var{thunk} returns normally, but not when
848 exited via an exception or new continuation. This ensures it's still
849 ready for use if @var{thunk} is re-entered by a captured continuation.
850 Of course the port is always garbage collected and closed in the usual
851 way when no longer referenced anywhere.
852 @end deffn
853
854 @deffn {Scheme Procedure} port-mode port
855 @deffnx {C Function} scm_port_mode (port)
856 Return the port modes associated with the open port @var{port}.
857 These will not necessarily be identical to the modes used when
858 the port was opened, since modes such as "append" which are
859 used only during port creation are not retained.
860 @end deffn
861
862 @deffn {Scheme Procedure} port-filename port
863 @deffnx {C Function} scm_port_filename (port)
864 Return the filename associated with @var{port}. This function returns
865 the strings "standard input", "standard output" and "standard error"
866 when called on the current input, output and error ports respectively.
867
868 @var{port} must be open, @code{port-filename} cannot be used once the
869 port is closed.
870 @end deffn
871
872 @deffn {Scheme Procedure} set-port-filename! port filename
873 @deffnx {C Function} scm_set_port_filename_x (port, filename)
874 Change the filename associated with @var{port}, using the current input
875 port if none is specified. Note that this does not change the port's
876 source of data, but only the value that is returned by
877 @code{port-filename} and reported in diagnostic output.
878 @end deffn
879
880 @deffn {Scheme Procedure} file-port? obj
881 @deffnx {C Function} scm_file_port_p (obj)
882 Determine whether @var{obj} is a port that is related to a file.
883 @end deffn
884
885
886 @node String Ports
887 @subsubsection String Ports
888 @cindex String port
889 @cindex Port, string
890
891 The following allow string ports to be opened by analogy to R4R*
892 file port facilities:
893
894 @deffn {Scheme Procedure} call-with-output-string proc
895 @deffnx {C Function} scm_call_with_output_string (proc)
896 Calls the one-argument procedure @var{proc} with a newly created output
897 port. When the function returns, the string composed of the characters
898 written into the port is returned. @var{proc} should not close the port.
899 @end deffn
900
901 @deffn {Scheme Procedure} call-with-input-string string proc
902 @deffnx {C Function} scm_call_with_input_string (string, proc)
903 Calls the one-argument procedure @var{proc} with a newly
904 created input port from which @var{string}'s contents may be
905 read. The value yielded by the @var{proc} is returned.
906 @end deffn
907
908 @deffn {Scheme Procedure} with-output-to-string thunk
909 Calls the zero-argument procedure @var{thunk} with the current output
910 port set temporarily to a new string port. It returns a string
911 composed of the characters written to the current output.
912 @end deffn
913
914 @deffn {Scheme Procedure} with-input-from-string string thunk
915 Calls the zero-argument procedure @var{thunk} with the current input
916 port set temporarily to a string port opened on the specified
917 @var{string}. The value yielded by @var{thunk} is returned.
918 @end deffn
919
920 @deffn {Scheme Procedure} open-input-string str
921 @deffnx {C Function} scm_open_input_string (str)
922 Take a string and return an input port that delivers characters
923 from the string. The port can be closed by
924 @code{close-input-port}, though its storage will be reclaimed
925 by the garbage collector if it becomes inaccessible.
926 @end deffn
927
928 @deffn {Scheme Procedure} open-output-string
929 @deffnx {C Function} scm_open_output_string ()
930 Return an output port that will accumulate characters for
931 retrieval by @code{get-output-string}. The port can be closed
932 by the procedure @code{close-output-port}, though its storage
933 will be reclaimed by the garbage collector if it becomes
934 inaccessible.
935 @end deffn
936
937 @deffn {Scheme Procedure} get-output-string port
938 @deffnx {C Function} scm_get_output_string (port)
939 Given an output port created by @code{open-output-string},
940 return a string consisting of the characters that have been
941 output to the port so far.
942
943 @code{get-output-string} must be used before closing @var{port}, once
944 closed the string cannot be obtained.
945 @end deffn
946
947 A string port can be used in many procedures which accept a port
948 but which are not dependent on implementation details of fports.
949 E.g., seeking and truncating will work on a string port,
950 but trying to extract the file descriptor number will fail.
951
952
953 @node Soft Ports
954 @subsubsection Soft Ports
955 @cindex Soft port
956 @cindex Port, soft
957
958 A @dfn{soft-port} is a port based on a vector of procedures capable of
959 accepting or delivering characters. It allows emulation of I/O ports.
960
961 @deffn {Scheme Procedure} make-soft-port pv modes
962 @deffnx {C Function} scm_make_soft_port (pv, modes)
963 Return a port capable of receiving or delivering characters as
964 specified by the @var{modes} string (@pxref{File Ports,
965 open-file}). @var{pv} must be a vector of length 5 or 6. Its
966 components are as follows:
967
968 @enumerate 0
969 @item
970 procedure accepting one character for output
971 @item
972 procedure accepting a string for output
973 @item
974 thunk for flushing output
975 @item
976 thunk for getting one character
977 @item
978 thunk for closing port (not by garbage collection)
979 @item
980 (if present and not @code{#f}) thunk for computing the number of
981 characters that can be read from the port without blocking.
982 @end enumerate
983
984 For an output-only port only elements 0, 1, 2, and 4 need be
985 procedures. For an input-only port only elements 3 and 4 need
986 be procedures. Thunks 2 and 4 can instead be @code{#f} if
987 there is no useful operation for them to perform.
988
989 If thunk 3 returns @code{#f} or an @code{eof-object}
990 (@pxref{Input, eof-object?, ,r5rs, The Revised^5 Report on
991 Scheme}) it indicates that the port has reached end-of-file.
992 For example:
993
994 @lisp
995 (define stdout (current-output-port))
996 (define p (make-soft-port
997 (vector
998 (lambda (c) (write c stdout))
999 (lambda (s) (display s stdout))
1000 (lambda () (display "." stdout))
1001 (lambda () (char-upcase (read-char)))
1002 (lambda () (display "@@" stdout)))
1003 "rw"))
1004
1005 (write p p) @result{} #<input-output: soft 8081e20>
1006 @end lisp
1007 @end deffn
1008
1009
1010 @node Void Ports
1011 @subsubsection Void Ports
1012 @cindex Void port
1013 @cindex Port, void
1014
1015 This kind of port causes any data to be discarded when written to, and
1016 always returns the end-of-file object when read from.
1017
1018 @deffn {Scheme Procedure} %make-void-port mode
1019 @deffnx {C Function} scm_sys_make_void_port (mode)
1020 Create and return a new void port. A void port acts like
1021 @file{/dev/null}. The @var{mode} argument
1022 specifies the input/output modes for this port: see the
1023 documentation for @code{open-file} in @ref{File Ports}.
1024 @end deffn
1025
1026
1027 @node R6RS I/O Ports
1028 @subsection R6RS I/O Ports
1029
1030 @cindex R6RS
1031 @cindex R6RS ports
1032
1033 The I/O port API of the @uref{http://www.r6rs.org/, Revised Report^6 on
1034 the Algorithmic Language Scheme (R6RS)} is provided by the @code{(rnrs
1035 io ports)} module. It provides features, such as binary I/O and Unicode
1036 string I/O, that complement or refine Guile's historical port API
1037 presented above (@pxref{Input and Output}).
1038
1039 @c FIXME: Update description when implemented.
1040 @emph{Note}: The implementation of this R6RS API is currently far from
1041 complete, notably due to the lack of support for Unicode I/O and strings.
1042
1043 @menu
1044 * R6RS End-of-File:: The end-of-file object.
1045 * R6RS Port Manipulation:: Manipulating R6RS ports.
1046 * R6RS Binary Input:: Binary input.
1047 * R6RS Binary Output:: Binary output.
1048 @end menu
1049
1050 @node R6RS End-of-File
1051 @subsubsection The End-of-File Object
1052
1053 @cindex EOF
1054 @cindex end-of-file
1055
1056 R5RS' @code{eof-object?} procedure is provided by the @code{(rnrs io
1057 ports)} module:
1058
1059 @deffn {Scheme Procedure} eof-object? obj
1060 @deffnx {C Function} scm_eof_object_p (obj)
1061 Return true if @var{obj} is the end-of-file (EOF) object.
1062 @end deffn
1063
1064 In addition, the following procedure is provided:
1065
1066 @deffn {Scheme Procedure} eof-object
1067 @deffnx {C Function} scm_eof_object ()
1068 Return the end-of-file (EOF) object.
1069
1070 @lisp
1071 (eof-object? (eof-object))
1072 @result{} #t
1073 @end lisp
1074 @end deffn
1075
1076
1077 @node R6RS Port Manipulation
1078 @subsubsection Port Manipulation
1079
1080 The procedures listed below operate on any kind of R6RS I/O port.
1081
1082 @deffn {Scheme Procedure} port-position port
1083 If @var{port} supports it (see below), return the offset (an integer)
1084 indicating where the next octet will be read from/written to in
1085 @var{port}. If @var{port} does not support this operation, an error
1086 condition is raised.
1087
1088 This is similar to Guile's @code{seek} procedure with the
1089 @code{SEEK_CUR} argument (@pxref{Random Access}).
1090 @end deffn
1091
1092 @deffn {Scheme Procedure} port-has-port-position? port
1093 Return @code{#t} is @var{port} supports @code{port-position}.
1094 @end deffn
1095
1096 @deffn {Scheme Procedure} set-port-position! port offset
1097 If @var{port} supports it (see below), set the position where the next
1098 octet will be read from/written to @var{port} to @var{offset} (an
1099 integer). If @var{port} does not support this operation, an error
1100 condition is raised.
1101
1102 This is similar to Guile's @code{seek} procedure with the
1103 @code{SEEK_SET} argument (@pxref{Random Access}).
1104 @end deffn
1105
1106 @deffn {Scheme Procedure} port-has-set-port-position!? port
1107 Return @code{#t} is @var{port} supports @code{set-port-position!}.
1108 @end deffn
1109
1110 @deffn {Scheme Procedure} call-with-port port proc
1111 Call @var{proc}, passing it @var{port} and closing @var{port} upon exit
1112 of @var{proc}. Return the return values of @var{proc}.
1113 @end deffn
1114
1115
1116 @node R6RS Binary Input
1117 @subsubsection Binary Input
1118
1119 @cindex binary input
1120
1121 R6RS binary input ports can be created with the procedures described
1122 below.
1123
1124 @deffn {Scheme Procedure} open-bytevector-input-port bv [transcoder]
1125 @deffnx {C Function} scm_open_bytevector_input_port (bv, transcoder)
1126 Return an input port whose contents are drawn from bytevector @var{bv}
1127 (@pxref{Bytevectors}).
1128
1129 @c FIXME: Update description when implemented.
1130 The @var{transcoder} argument is currently not supported.
1131 @end deffn
1132
1133 @cindex custom binary input ports
1134
1135 @deffn {Scheme Procedure} make-custom-binary-input-port id read! get-position set-position! close
1136 @deffnx {C Function} scm_make_custom_binary_input_port (id, read!, get-position, set-position!, close)
1137 Return a new custom binary input port@footnote{This is similar in spirit
1138 to Guile's @dfn{soft ports} (@pxref{Soft Ports}).} named @var{id} (a
1139 string) whose input is drained by invoking @var{read!} and passing it a
1140 bytevector, an index where bytes should be written, and the number of
1141 bytes to read. The @code{read!} procedure must return an integer
1142 indicating the number of bytes read, or @code{0} to indicate the
1143 end-of-file.
1144
1145 Optionally, if @var{get-position} is not @code{#f}, it must be a thunk
1146 that will be called when @var{port-position} is invoked on the custom
1147 binary port and should return an integer indicating the position within
1148 the underlying data stream; if @var{get-position} was not supplied, the
1149 returned port does not support @var{port-position}.
1150
1151 Likewise, if @var{set-position!} is not @code{#f}, it should be a
1152 one-argument procedure. When @var{set-port-position!} is invoked on the
1153 custom binary input port, @var{set-position!} is passed an integer
1154 indicating the position of the next byte is to read.
1155
1156 Finally, if @var{close} is not @code{#f}, it must be a thunk. It is
1157 invoked when the custom binary input port is closed.
1158
1159 Using a custom binary input port, the @code{open-bytevector-input-port}
1160 procedure could be implemented as follows:
1161
1162 @lisp
1163 (define (open-bytevector-input-port source)
1164 (define position 0)
1165 (define length (bytevector-length source))
1166
1167 (define (read! bv start count)
1168 (let ((count (min count (- length position))))
1169 (bytevector-copy! source position
1170 bv start count)
1171 (set! position (+ position count))
1172 count))
1173
1174 (define (get-position) position)
1175
1176 (define (set-position! new-position)
1177 (set! position new-position))
1178
1179 (make-custom-binary-input-port "the port" read!
1180 get-position
1181 set-position!))
1182
1183 (read (open-bytevector-input-port (string->utf8 "hello")))
1184 @result{} hello
1185 @end lisp
1186 @end deffn
1187
1188 @cindex binary input
1189 Binary input is achieved using the procedures below:
1190
1191 @deffn {Scheme Procedure} get-u8 port
1192 @deffnx {C Function} scm_get_u8 (port)
1193 Return an octet read from @var{port}, a binary input port, blocking as
1194 necessary, or the end-of-file object.
1195 @end deffn
1196
1197 @deffn {Scheme Procedure} lookahead-u8 port
1198 @deffnx {C Function} scm_lookahead_u8 (port)
1199 Like @code{get-u8} but does not update @var{port}'s position to point
1200 past the octet.
1201 @end deffn
1202
1203 @deffn {Scheme Procedure} get-bytevector-n port count
1204 @deffnx {C Function} scm_get_bytevector_n (port, count)
1205 Read @var{count} octets from @var{port}, blocking as necessary and
1206 return a bytevector containing the octets read. If fewer bytes are
1207 available, a bytevector smaller than @var{count} is returned.
1208 @end deffn
1209
1210 @deffn {Scheme Procedure} get-bytevector-n! port bv start count
1211 @deffnx {C Function} scm_get_bytevector_n_x (port, bv, start, count)
1212 Read @var{count} bytes from @var{port} and store them in @var{bv}
1213 starting at index @var{start}. Return either the number of bytes
1214 actually read or the end-of-file object.
1215 @end deffn
1216
1217 @deffn {Scheme Procedure} get-bytevector-some port
1218 @deffnx {C Function} scm_get_bytevector_some (port)
1219 Read from @var{port}, blocking as necessary, until data are available or
1220 and end-of-file is reached. Return either a new bytevector containing
1221 the data read or the end-of-file object.
1222 @end deffn
1223
1224 @deffn {Scheme Procedure} get-bytevector-all port
1225 @deffnx {C Function} scm_get_bytevector_all (port)
1226 Read from @var{port}, blocking as necessary, until the end-of-file is
1227 reached. Return either a new bytevector containing the data read or the
1228 end-of-file object (if no data were available).
1229 @end deffn
1230
1231 @node R6RS Binary Output
1232 @subsubsection Binary Output
1233
1234 Binary output ports can be created with the procedures below.
1235
1236 @deffn {Scheme Procedure} open-bytevector-output-port [transcoder]
1237 @deffnx {C Function} scm_open_bytevector_output_port (transcoder)
1238 Return two values: a binary output port and a procedure. The latter
1239 should be called with zero arguments to obtain a bytevector containing
1240 the data accumulated by the port, as illustrated below.
1241
1242 @lisp
1243 (call-with-values
1244 (lambda ()
1245 (open-bytevector-output-port))
1246 (lambda (port get-bytevector)
1247 (display "hello" port)
1248 (get-bytevector)))
1249
1250 @result{} #vu8(104 101 108 108 111)
1251 @end lisp
1252
1253 @c FIXME: Update description when implemented.
1254 The @var{transcoder} argument is currently not supported.
1255 @end deffn
1256
1257 @cindex custom binary output ports
1258
1259 @deffn {Scheme Procedure} make-custom-binary-output-port id write! get-position set-position! close
1260 @deffnx {C Function} scm_make_custom_binary_output_port (id, write!, get-position, set-position!, close)
1261 Return a new custom binary output port named @var{id} (a string) whose
1262 output is sunk by invoking @var{write!} and passing it a bytevector, an
1263 index where bytes should be read from this bytevector, and the number of
1264 bytes to be ``written''. The @code{write!} procedure must return an
1265 integer indicating the number of bytes actually written; when it is
1266 passed @code{0} as the number of bytes to write, it should behave as
1267 though an end-of-file was sent to the byte sink.
1268
1269 The other arguments are as for @code{make-custom-binary-input-port}
1270 (@pxref{R6RS Binary Input, @code{make-custom-binary-input-port}}).
1271 @end deffn
1272
1273 @cindex binary output
1274 Writing to a binary output port can be done using the following
1275 procedures:
1276
1277 @deffn {Scheme Procedure} put-u8 port octet
1278 @deffnx {C Function} scm_put_u8 (port, octet)
1279 Write @var{octet}, an integer in the 0--255 range, to @var{port}, a
1280 binary output port.
1281 @end deffn
1282
1283 @deffn {Scheme Procedure} put-bytevector port bv [start [count]]
1284 @deffnx {C Function} scm_put_bytevector (port, bv, start, count)
1285 Write the contents of @var{bv} to @var{port}, optionally starting at
1286 index @var{start} and limiting to @var{count} octets.
1287 @end deffn
1288
1289
1290 @node I/O Extensions
1291 @subsection Using and Extending Ports in C
1292
1293 @menu
1294 * C Port Interface:: Using ports from C.
1295 * Port Implementation:: How to implement a new port type in C.
1296 @end menu
1297
1298
1299 @node C Port Interface
1300 @subsubsection C Port Interface
1301 @cindex C port interface
1302 @cindex Port, C interface
1303
1304 This section describes how to use Scheme ports from C.
1305
1306 @subsubheading Port basics
1307
1308 @cindex ptob
1309 @tindex scm_ptob_descriptor
1310 @tindex scm_port
1311 @findex SCM_PTAB_ENTRY
1312 @findex SCM_PTOBNUM
1313 @vindex scm_ptobs
1314 There are two main data structures. A port type object (ptob) is of
1315 type @code{scm_ptob_descriptor}. A port instance is of type
1316 @code{scm_port}. Given an @code{SCM} variable which points to a port,
1317 the corresponding C port object can be obtained using the
1318 @code{SCM_PTAB_ENTRY} macro. The ptob can be obtained by using
1319 @code{SCM_PTOBNUM} to give an index into the @code{scm_ptobs}
1320 global array.
1321
1322 @subsubheading Port buffers
1323
1324 An input port always has a read buffer and an output port always has a
1325 write buffer. However the size of these buffers is not guaranteed to be
1326 more than one byte (e.g., the @code{shortbuf} field in @code{scm_port}
1327 which is used when no other buffer is allocated). The way in which the
1328 buffers are allocated depends on the implementation of the ptob. For
1329 example in the case of an fport, buffers may be allocated with malloc
1330 when the port is created, but in the case of an strport the underlying
1331 string is used as the buffer.
1332
1333 @subsubheading The @code{rw_random} flag
1334
1335 Special treatment is required for ports which can be seeked at random.
1336 Before various operations, such as seeking the port or changing from
1337 input to output on a bidirectional port or vice versa, the port
1338 implementation must be given a chance to update its state. The write
1339 buffer is updated by calling the @code{flush} ptob procedure and the
1340 input buffer is updated by calling the @code{end_input} ptob procedure.
1341 In the case of an fport, @code{flush} causes buffered output to be
1342 written to the file descriptor, while @code{end_input} causes the
1343 descriptor position to be adjusted to account for buffered input which
1344 was never read.
1345
1346 The special treatment must be performed if the @code{rw_random} flag in
1347 the port is non-zero.
1348
1349 @subsubheading The @code{rw_active} variable
1350
1351 The @code{rw_active} variable in the port is only used if
1352 @code{rw_random} is set. It's defined as an enum with the following
1353 values:
1354
1355 @table @code
1356 @item SCM_PORT_READ
1357 the read buffer may have unread data.
1358
1359 @item SCM_PORT_WRITE
1360 the write buffer may have unwritten data.
1361
1362 @item SCM_PORT_NEITHER
1363 neither the write nor the read buffer has data.
1364 @end table
1365
1366 @subsubheading Reading from a port.
1367
1368 To read from a port, it's possible to either call existing libguile
1369 procedures such as @code{scm_getc} and @code{scm_read_line} or to read
1370 data from the read buffer directly. Reading from the buffer involves
1371 the following steps:
1372
1373 @enumerate
1374 @item
1375 Flush output on the port, if @code{rw_active} is @code{SCM_PORT_WRITE}.
1376
1377 @item
1378 Fill the read buffer, if it's empty, using @code{scm_fill_input}.
1379
1380 @item Read the data from the buffer and update the read position in
1381 the buffer. Steps 2) and 3) may be repeated as many times as required.
1382
1383 @item Set rw_active to @code{SCM_PORT_READ} if @code{rw_random} is set.
1384
1385 @item update the port's line and column counts.
1386 @end enumerate
1387
1388 @subsubheading Writing to a port.
1389
1390 To write data to a port, calling @code{scm_lfwrite} should be sufficient for
1391 most purposes. This takes care of the following steps:
1392
1393 @enumerate
1394 @item
1395 End input on the port, if @code{rw_active} is @code{SCM_PORT_READ}.
1396
1397 @item
1398 Pass the data to the ptob implementation using the @code{write} ptob
1399 procedure. The advantage of using the ptob @code{write} instead of
1400 manipulating the write buffer directly is that it allows the data to be
1401 written in one operation even if the port is using the single-byte
1402 @code{shortbuf}.
1403
1404 @item
1405 Set @code{rw_active} to @code{SCM_PORT_WRITE} if @code{rw_random}
1406 is set.
1407 @end enumerate
1408
1409
1410 @node Port Implementation
1411 @subsubsection Port Implementation
1412 @cindex Port implemenation
1413
1414 This section describes how to implement a new port type in C.
1415
1416 As described in the previous section, a port type object (ptob) is
1417 a structure of type @code{scm_ptob_descriptor}. A ptob is created by
1418 calling @code{scm_make_port_type}.
1419
1420 @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))
1421 Return a new port type object. The @var{name}, @var{fill_input} and
1422 @var{write} parameters are initial values for those port type fields,
1423 as described below. The other fields are initialized with default
1424 values and can be changed later.
1425 @end deftypefun
1426
1427 All of the elements of the ptob, apart from @code{name}, are procedures
1428 which collectively implement the port behaviour. Creating a new port
1429 type mostly involves writing these procedures.
1430
1431 @table @code
1432 @item name
1433 A pointer to a NUL terminated string: the name of the port type. This
1434 is the only element of @code{scm_ptob_descriptor} which is not
1435 a procedure. Set via the first argument to @code{scm_make_port_type}.
1436
1437 @item mark
1438 Called during garbage collection to mark any SCM objects that a port
1439 object may contain. It doesn't need to be set unless the port has
1440 @code{SCM} components. Set using
1441
1442 @deftypefun void scm_set_port_mark (scm_t_bits tc, SCM (*mark) (SCM port))
1443 @end deftypefun
1444
1445 @item free
1446 Called when the port is collected during gc. It
1447 should free any resources used by the port.
1448 Set using
1449
1450 @deftypefun void scm_set_port_free (scm_t_bits tc, size_t (*free) (SCM port))
1451 @end deftypefun
1452
1453 @item print
1454 Called when @code{write} is called on the port object, to print a
1455 port description. E.g., for an fport it may produce something like:
1456 @code{#<input: /etc/passwd 3>}. Set using
1457
1458 @deftypefun void scm_set_port_print (scm_t_bits tc, int (*print) (SCM port, SCM dest_port, scm_print_state *pstate))
1459 The first argument @var{port} is the object being printed, the second
1460 argument @var{dest_port} is where its description should go.
1461 @end deftypefun
1462
1463 @item equalp
1464 Not used at present. Set using
1465
1466 @deftypefun void scm_set_port_equalp (scm_t_bits tc, SCM (*equalp) (SCM, SCM))
1467 @end deftypefun
1468
1469 @item close
1470 Called when the port is closed, unless it was collected during gc. It
1471 should free any resources used by the port.
1472 Set using
1473
1474 @deftypefun void scm_set_port_close (scm_t_bits tc, int (*close) (SCM port))
1475 @end deftypefun
1476
1477 @item write
1478 Accept data which is to be written using the port. The port implementation
1479 may choose to buffer the data instead of processing it directly.
1480 Set via the third argument to @code{scm_make_port_type}.
1481
1482 @item flush
1483 Complete the processing of buffered output data. Reset the value of
1484 @code{rw_active} to @code{SCM_PORT_NEITHER}.
1485 Set using
1486
1487 @deftypefun void scm_set_port_flush (scm_t_bits tc, void (*flush) (SCM port))
1488 @end deftypefun
1489
1490 @item end_input
1491 Perform any synchronization required when switching from input to output
1492 on the port. Reset the value of @code{rw_active} to @code{SCM_PORT_NEITHER}.
1493 Set using
1494
1495 @deftypefun void scm_set_port_end_input (scm_t_bits tc, void (*end_input) (SCM port, int offset))
1496 @end deftypefun
1497
1498 @item fill_input
1499 Read new data into the read buffer and return the first character. It
1500 can be assumed that the read buffer is empty when this procedure is called.
1501 Set via the second argument to @code{scm_make_port_type}.
1502
1503 @item input_waiting
1504 Return a lower bound on the number of bytes that could be read from the
1505 port without blocking. It can be assumed that the current state of
1506 @code{rw_active} is @code{SCM_PORT_NEITHER}.
1507 Set using
1508
1509 @deftypefun void scm_set_port_input_waiting (scm_t_bits tc, int (*input_waiting) (SCM port))
1510 @end deftypefun
1511
1512 @item seek
1513 Set the current position of the port. The procedure can not make
1514 any assumptions about the value of @code{rw_active} when it's
1515 called. It can reset the buffers first if desired by using something
1516 like:
1517
1518 @example
1519 if (pt->rw_active == SCM_PORT_READ)
1520 scm_end_input (port);
1521 else if (pt->rw_active == SCM_PORT_WRITE)
1522 ptob->flush (port);
1523 @end example
1524
1525 However note that this will have the side effect of discarding any data
1526 in the unread-char buffer, in addition to any side effects from the
1527 @code{end_input} and @code{flush} ptob procedures. This is undesirable
1528 when seek is called to measure the current position of the port, i.e.,
1529 @code{(seek p 0 SEEK_CUR)}. The libguile fport and string port
1530 implementations take care to avoid this problem.
1531
1532 The procedure is set using
1533
1534 @deftypefun void scm_set_port_seek (scm_t_bits tc, scm_t_off (*seek) (SCM port, scm_t_off offset, int whence))
1535 @end deftypefun
1536
1537 @item truncate
1538 Truncate the port data to be specified length. It can be assumed that the
1539 current state of @code{rw_active} is @code{SCM_PORT_NEITHER}.
1540 Set using
1541
1542 @deftypefun void scm_set_port_truncate (scm_t_bits tc, void (*truncate) (SCM port, scm_t_off length))
1543 @end deftypefun
1544
1545 @end table
1546
1547
1548 @c Local Variables:
1549 @c TeX-master: "guile.texi"
1550 @c End: