Use @result{} instead of -->
[bpt/guile.git] / doc / ref / api-io.texi
CommitLineData
07d83abe
MV
1@c -*-texinfo-*-
2@c This is part of the GNU Guile Reference Manual.
b242715b 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2009
07d83abe
MV
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.
b242715b 21* R6RS I/O Ports:: The R6RS port API.
07d83abe
MV
22* I/O Extensions:: Using and extending ports in C.
23@end menu
24
25
26@node Ports
27@subsection Ports
bf5df489 28@cindex Port
07d83abe
MV
29
30Sequential input/output in Scheme is represented by operations on a
31@dfn{port}. This chapter explains the operations that Guile provides
32for working with ports.
33
34Ports 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
36written to an output port, or both on an input/output port. A port
37can be closed (@pxref{Closing}) when no longer required, after which
38any attempt to read or write is an error.
39
40The formal definition of a port is very generic: an input port is
41simply ``an object which can deliver characters on demand,'' and an
42output port is ``an object which can accept characters.'' Because
43this definition is so loose, it is easy to write functions that
44simulate ports in software. @dfn{Soft ports} and @dfn{string ports}
45are two interesting and powerful examples of this technique.
46(@pxref{Soft Ports}, and @ref{String Ports}.)
47
48Ports are garbage collected in the usual way (@pxref{Memory
49Management}), and will be closed at that time if not already closed.
50In this case any errors occuring in the close will not be reported.
51Usually a program will want to explicitly close so as to be sure all
52its operations have been successful. Of course if a program has
53abandoned something due to an error or other condition then closing
54problems are probably not of interest.
55
56It is strongly recommended that file ports be closed explicitly when
57no longer required. Most systems have limits on how many files can be
58open, both on a per-process and a system-wide basis. A program that
59uses many files should take care not to hit those limits. The same
60applies to similar system resources such as pipes and sockets.
61
62Note that automatic garbage collection is triggered only by memory
63consumption, not by file or other resource usage, so a program cannot
64rely 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.
66If program flow makes it hard to be certain when to close then this
67may be an acceptable way to control resource usage.
68
40296bab
KR
69All file access uses the ``LFS'' large file support functions when
70available, so files bigger than 2 Gbytes (@math{2^31} bytes) can be
71read and written on a 32-bit system.
72
07d83abe
MV
73@rnindex input-port?
74@deffn {Scheme Procedure} input-port? x
75@deffnx {C Function} scm_input_port_p (x)
76Return @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)
84Return @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)
91Return a boolean indicating whether @var{x} is a port.
92Equivalent to @code{(or (input-port? @var{x}) (output-port?
93@var{x}))}.
94@end deffn
95
96
97@node Reading
98@subsection Reading
bf5df489 99@cindex Reading
07d83abe
MV
100
101[Generic procedures for reading from ports.]
102
103@rnindex eof-object?
bf5df489 104@cindex End of file object
07d83abe
MV
105@deffn {Scheme Procedure} eof-object? x
106@deffnx {C Function} scm_eof_object_p (x)
107Return @code{#t} if @var{x} is an end-of-file object; otherwise
108return @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)
114Return @code{#t} if a character is ready on input @var{port}
115and 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
118port at end of file then @code{char-ready?} returns @code{#t}.
cdf1ad3b
MV
119
120@code{char-ready?} exists to make it possible for a
07d83abe
MV
121program to accept characters from interactive ports without
122getting stuck waiting for input. Any input editors associated
123with such ports must make sure that characters whose existence
124has been asserted by @code{char-ready?} cannot be rubbed out.
125If @code{char-ready?} were to return @code{#f} at end of file,
126a port at end of file would be indistinguishable from an
cdf1ad3b 127interactive port that has no ready characters.
07d83abe
MV
128@end deffn
129
130@rnindex read-char
131@deffn {Scheme Procedure} read-char [port]
132@deffnx {C Function} scm_read_char (port)
133Return the next character available from @var{port}, updating
134@var{port} to point to the following character. If no more
135characters 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)
139Read 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,
141which can be less than @var{size} if end-of-file has been reached.
142
143Note 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)
150Return the next character available from @var{port},
151@emph{without} updating @var{port} to point to the following
152character. If no more characters are available, the
cdf1ad3b
MV
153end-of-file object is returned.
154
155The value returned by
07d83abe
MV
156a call to @code{peek-char} is the same as the value that would
157have been returned by a call to @code{read-char} on the same
158port. The only difference is that the very next call to
159@code{read-char} or @code{peek-char} on that @var{port} will
160return the value returned by the preceding call to
161@code{peek-char}. In particular, a call to @code{peek-char} on
162an interactive port will hang waiting for input whenever a call
cdf1ad3b 163to @code{read-char} would have hung.
07d83abe
MV
164@end deffn
165
166@deffn {Scheme Procedure} unread-char cobj [port]
167@deffnx {C Function} scm_unread_char (cobj, port)
168Place @var{char} in @var{port} so that it will be read by the
169next read operation. If called multiple times, the unread characters
170will be read again in last-in first-out order. If @var{port} is
171not 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)
176Place the string @var{str} in @var{port} so that its characters will
177be read from left-to-right as the next characters from @var{port}
178during subsequent read operations. If called multiple times, the
179unread characters will be read again in last-in first-out order. If
9782da8a 180@var{port} is not supplied, the @code{current-input-port} is used.
07d83abe
MV
181@end deffn
182
183@deffn {Scheme Procedure} drain-input port
184@deffnx {C Function} scm_drain_input (port)
185This procedure clears a port's input buffers, similar
186to the way that force-output clears the output buffer. The
187contents 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
196Draining the buffers may be useful for cleanly finishing
197buffered I/O so that the file descriptor can be used directly
198for 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)
205Return the current column number or line number of @var{port}.
206If the number is
207unknown, 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
210message, we recommend you add 1 to get 1-origin integers. This is
211because lines and column numbers traditionally start with 1, and that is
212what 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)
219Set the current column or line number of @var{port}.
220@end deffn
221
222@node Writing
223@subsection Writing
bf5df489 224@cindex Writing
07d83abe
MV
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)
230Return the print state of the port @var{port}. If @var{port}
231has no associated print state, @code{#f} is returned.
232@end deffn
233
234@rnindex write
235@deffn {Scheme Procedure} write obj [port]
236Send a representation of @var{obj} to @var{port} or to the current
237output port if not given.
238
239The output is designed to be machine readable, and can be read back
240with @code{read} (@pxref{Reading}). Strings are printed in
241doublequotes, 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]
247Send a representation of @var{obj} to @var{port} or to the current
248output port if not given.
249
250The output is designed for human readability, it differs from
251@code{write} in that strings are printed without doublequotes and
252escapes, 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)
259Send a newline to @var{port}.
260If @var{port} is omitted, send to the current output port.
261@end deffn
262
cdf1ad3b 263@deffn {Scheme Procedure} port-with-print-state port [pstate]
07d83abe
MV
264@deffnx {C Function} scm_port_with_print_state (port, pstate)
265Create a new port which behaves like @var{port}, but with an
cdf1ad3b
MV
266included print state @var{pstate}. @var{pstate} is optional.
267If @var{pstate} isn't supplied and @var{port} already has
268a print state, the old print state is reused.
07d83abe
MV
269@end deffn
270
271@deffn {Scheme Procedure} print-options-interface [setting]
272@deffnx {C Function} scm_print_options (setting)
273Option interface for the print options. Instead of using
274this procedure directly, use the procedures
275@code{print-enable}, @code{print-disable}, @code{print-set!}
276and @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)
281Write @var{message} to @var{destination}, defaulting to
282the current output port.
283@var{message} can contain @code{~A} (was @code{%s}) and
284@code{~S} (was @code{%S}) escapes. When printed,
285the escapes are replaced with corresponding members of
286@var{ARGS}:
287@code{~A} formats using @code{display} and @code{~S} formats
288using @code{write}.
289If @var{destination} is @code{#t}, then use the current output
290port, if @var{destination} is @code{#f}, then return a string
291containing 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)
297Send 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)
301Write @var{size} bytes at @var{buffer} to @var{port}.
302
303Note 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)
310Flush the specified output port, or the current output port if @var{port}
311is omitted. The current output buffer contents are passed to the
312underlying port implementation (e.g., in the case of fports, the
313data will be written to the file and the output buffer will be cleared.)
314It has no effect on an unbuffered port.
315
316The return value is unspecified.
317@end deffn
318
319@deffn {Scheme Procedure} flush-all-ports
320@deffnx {C Function} scm_flush_all_ports ()
321Equivalent to calling @code{force-output} on
322all open output ports. The return value is unspecified.
323@end deffn
324
325
326@node Closing
327@subsection Closing
bf5df489
KR
328@cindex Closing ports
329@cindex Port, close
07d83abe
MV
330
331@deffn {Scheme Procedure} close-port port
332@deffnx {C Function} scm_close_port (port)
333Close the specified port object. Return @code{#t} if it
334successfully closes a port or @code{#f} if it was already
335closed. An exception may be raised if an error occurs, for
336example when flushing buffered output. See also @ref{Ports and
337File Descriptors, close}, for a procedure which can close file
338descriptors.
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
347Close the specified input or output @var{port}. An exception may be
348raised if an error occurs while closing. If @var{port} is already
349closed, nothing is done. The return value is unspecified.
350
351See also @ref{Ports and File Descriptors, close}, for a procedure
352which can close file descriptors.
353@end deffn
354
355@deffn {Scheme Procedure} port-closed? port
356@deffnx {C Function} scm_port_closed_p (port)
357Return @code{#t} if @var{port} is closed or @code{#f} if it is
358open.
359@end deffn
360
361
362@node Random Access
363@subsection Random Access
bf5df489
KR
364@cindex Random access, ports
365@cindex Port, random access
07d83abe
MV
366
367@deffn {Scheme Procedure} seek fd_port offset whence
368@deffnx {C Function} scm_seek (fd_port, offset, whence)
369Sets 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
373One of the following variables should be supplied for
374@var{whence}:
375@defvar SEEK_SET
376Seek from the beginning of the file.
377@end defvar
378@defvar SEEK_CUR
379Seek from the current position.
380@end defvar
381@defvar SEEK_END
382Seek from the end of the file.
383@end defvar
384If @var{fd/port} is a file descriptor, the underlying system
385call is @code{lseek}. @var{port} may be a string port.
386
387The value returned is the new position in the file. This means
388that 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)
396Return 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
40296bab
KR
406@deffn {Scheme Procedure} truncate-file file [length]
407@deffnx {C Function} scm_truncate_file (file, length)
408Truncate @var{file} to @var{length} bytes. @var{file} can be a
409filename string, a port object, or an integer file descriptor. The
410return value is unspecified.
411
412For a port or file descriptor @var{length} can be omitted, in which
413case the file is truncated at the current position (per @code{ftell}
414above).
415
416On most systems a file can be extended by giving a length greater than
417the current size, but this is not mandatory in the POSIX standard.
07d83abe
MV
418@end deffn
419
420@node Line/Delimited
421@subsection Line Oriented and Delimited Text
bf5df489
KR
422@cindex Line input/output
423@cindex Port, line input/output
07d83abe
MV
424
425The delimited-I/O module can be accessed with:
426
427@smalllisp
428(use-modules (ice-9 rdelim))
429@end smalllisp
430
431It can be used to read or write lines of text, or read text delimited by
432a specified set of characters. It's similar to the @code{(scsh rdelim)}
433module from guile-scsh, but does not use multiple values or character
434sets 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]
438Return a line of text from @var{port} if specified, otherwise from the
439value returned by @code{(current-input-port)}. Under Unix, a line of text
440is terminated by the first end-of-line character or by end-of-file.
441
442If @var{handle-delim} is specified, it should be one of the following
443symbols:
444@table @code
445@item trim
446Discard the terminating delimiter. This is the default, but it will
447be impossible to tell whether the read terminated with a delimiter or
448end-of-file.
449@item concat
450Append the terminating delimiter (if any) to the returned string.
451@item peek
452Push the terminating delimiter (if any) back on to the port.
453@item split
454Return a pair containing the string read from the port and the
455terminating 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]
461Read a line of text into the supplied string @var{buf} and return the
462number of characters added to @var{buf}. If @var{buf} is filled, then
463@code{#f} is returned.
464Read from @var{port} if
465specified, 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]
470Read text until one of the characters in the string @var{delims} is found
471or end-of-file is reached. Read from @var{port} if supplied, otherwise
472from 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]
478Read text into the supplied string @var{buf} and return the number of
479characters added to @var{buf} (subject to @var{handle-delim}, which takes
480the 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
482delimiter. Also terminates if one of the characters in the string
483@var{delims} is found
484or end-of-file is reached. Read from @var{port} if supplied, otherwise
485from 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)
490Display @var{obj} and a newline character to @var{port}. If
491@var{port} is not specified, @code{(current-output-port)} is
492used. This function is equivalent to:
493@lisp
494(display obj [port])
495(newline [port])
496@end lisp
497@end deffn
498
499Some of the abovementioned I/O functions rely on the following C
500primitives. These will mainly be of interest to people hacking Guile
501internals.
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)
505Read characters from @var{port} into @var{str} until one of the
506characters in the @var{delims} string is encountered. If
507@var{gobble} is true, discard the delimiter character;
508otherwise, 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
511specified, store data only into the substring of @var{str}
512bounded by @var{start} and @var{end} (which default to the
513beginning and end of the string, respectively).
514
515 Return a pair consisting of the delimiter that terminated the
516string and the number of characters read. If reading stopped
517at the end of file, the delimiter returned is the
518@var{eof-object}; if the string was filled without encountering
519a 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)
524Read a newline-terminated line from @var{port}, allocating storage as
525necessary. The newline terminator (if any) is removed from the string,
526and a pair consisting of the line and its delimiter is returned. The
527delimiter 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
bf5df489
KR
534@cindex Block read/write
535@cindex Port, block read/write
07d83abe
MV
536
537The Block-string-I/O module can be accessed with:
538
539@smalllisp
540(use-modules (ice-9 rw))
541@end smalllisp
542
543It 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)
548Read characters from a port or file descriptor into a
549string @var{str}. A port must have an underlying file
550descriptor --- a so-called fport. This procedure is
551scsh-compatible and can efficiently read large strings.
552It will:
553
554@itemize
555@item
556attempt to fill the entire string, unless the @var{start}
557and/or @var{end} arguments are supplied. i.e., @var{start}
558defaults to 0 and @var{end} defaults to
559@code{(string-length str)}
560@item
561use the current input port if @var{port_or_fdes} is not
562supplied.
563@item
564return fewer than the requested number of characters in some
565cases, e.g., on end of file, if interrupted by a signal, or if
566not all the characters are immediately available.
567@item
568wait indefinitely for some input if no characters are
569currently available,
570unless the port is in non-blocking mode.
571@item
572read characters from the port's input buffers if available,
573instead from the underlying file descriptor.
574@item
575return @code{#f} if end-of-file is encountered before reading
576any characters, otherwise return the number of characters
577read.
578@item
579return 0 if the port is in non-blocking mode and no characters
580are immediately available.
581@item
582return 0 if the request is for 0 bytes, with no
583end-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)
589Write characters from a string @var{str} to a port or file
590descriptor. A port must have an underlying file descriptor
591--- a so-called fport. This procedure is
592scsh-compatible and can efficiently write large strings.
593It will:
594
595@itemize
596@item
597attempt to write the entire string, unless the @var{start}
598and/or @var{end} arguments are supplied. i.e., @var{start}
599defaults to 0 and @var{end} defaults to
600@code{(string-length str)}
601@item
602use the current output port if @var{port_of_fdes} is not
603supplied.
604@item
605in the case of a buffered port, store the characters in the
606port's output buffer, if all will fit. If they will not fit
607then any existing buffered characters will be flushed
608before attempting
609to write the new characters directly to the underlying file
610descriptor. If the port is in non-blocking mode and
611buffered characters can not be flushed immediately, then an
612@code{EAGAIN} system-error exception will be raised (Note:
613scsh does not support the use of non-blocking buffered ports.)
614@item
615write fewer than the requested number of
616characters in some cases, e.g., if interrupted by a signal or
617if not all of the output can be accepted immediately.
618@item
619wait indefinitely for at least one character
620from @var{str} to be accepted by the port, unless the port is
621in non-blocking mode.
622@item
623return the number of characters accepted by the port.
624@item
625return 0 if the port is in non-blocking mode and can not accept
626at least one character from @var{str} immediately
627@item
628return 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
bf5df489
KR
634@cindex Default ports
635@cindex Port, default
07d83abe
MV
636
637@rnindex current-input-port
638@deffn {Scheme Procedure} current-input-port
639@deffnx {C Function} scm_current_input_port ()
34846414 640@cindex standard input
07d83abe 641Return the current input port. This is the default port used
3fa0a042
KR
642by many input procedures.
643
644Initially this is the @dfn{standard input} in Unix and C terminology.
645When the standard input is a tty the port is unbuffered, otherwise
646it's fully buffered.
647
648Unbuffered input is good if an application runs an interactive
649subprocess, since any type-ahead input won't go into Guile's buffer
9782da8a 650and be unavailable to the subprocess.
3fa0a042
KR
651
652Note that Guile buffering is completely separate from the tty ``line
9782da8a
KR
653discipline''. In the usual cooked mode on a tty Guile only sees a
654line of input once the user presses @key{Return}.
07d83abe
MV
655@end deffn
656
657@rnindex current-output-port
658@deffn {Scheme Procedure} current-output-port
659@deffnx {C Function} scm_current_output_port ()
34846414 660@cindex standard output
07d83abe 661Return the current output port. This is the default port used
3fa0a042
KR
662by many output procedures.
663
664Initially this is the @dfn{standard output} in Unix and C terminology.
665When the standard output is a tty this port is unbuffered, otherwise
666it's fully buffered.
667
668Unbuffered output to a tty is good for ensuring progress output or a
669prompt is seen. But an application which always prints whole lines
670could change to line buffered, or an application with a lot of output
671could go fully buffered and perhaps make explicit @code{force-output}
672calls (@pxref{Writing}) at selected points.
07d83abe
MV
673@end deffn
674
675@deffn {Scheme Procedure} current-error-port
676@deffnx {C Function} scm_current_error_port ()
34846414 677@cindex standard error output
3fa0a042
KR
678Return the port to which errors and warnings should be sent.
679
680Initially this is the @dfn{standard error} in Unix and C terminology.
681When the standard error is a tty this port is unbuffered, otherwise
682it's fully buffered.
07d83abe
MV
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)
691Change the ports returned by @code{current-input-port},
692@code{current-output-port} and @code{current-error-port}, respectively,
693so that they use the supplied @var{port} for input or output.
694@end deffn
695
661ae7ab
MV
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)
07d83abe 699These functions must be used inside a pair of calls to
661ae7ab
MV
700@code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
701Wind}). During the dynwind context, the indicated port is set to
07d83abe
MV
702@var{port}.
703
704More precisely, the current port is swapped with a `backup' value
661ae7ab 705whenever the dynwind context is entered or left. The backup value is
07d83abe
MV
706initialized with the @var{port} argument.
707@end deftypefn
708
709@node Port Types
710@subsection Types of Port
bf5df489
KR
711@cindex Types of ports
712@cindex Port, types
07d83abe
MV
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
bf5df489
KR
726@cindex File port
727@cindex Port, file
07d83abe
MV
728
729The following procedures are used to open file ports.
730See also @ref{Ports and File Descriptors, open}, for an interface
731to the Unix @code{open} system call.
732
733Most systems have limits on how many files can be open, so it's
734strongly recommended that file ports be closed explicitly when no
735longer required (@pxref{Ports}).
736
737@deffn {Scheme Procedure} open-file filename mode
738@deffnx {C Function} scm_open_file (filename, mode)
739Open the file whose name is @var{filename}, and return a port
740representing that file. The attributes of the port are
741determined by the @var{mode} string. The way in which this is
742interpreted is similar to C stdio. The first character must be
743one of the following:
c755b861 744
07d83abe
MV
745@table @samp
746@item r
747Open an existing file for input.
748@item w
749Open a file for output, creating it if it doesn't already exist
750or removing its contents if it does.
751@item a
752Open a file for output, creating it if it doesn't already
753exist. All writes to the port will go to the end of the file.
754The "append mode" can be turned off while the port is in use
755@pxref{Ports and File Descriptors, fcntl}
756@end table
c755b861 757
07d83abe 758The following additional characters can be appended:
c755b861 759
07d83abe
MV
760@table @samp
761@item +
762Open the port for both input and output. E.g., @code{r+}: open
763an existing file for both input and output.
764@item 0
765Create an "unbuffered" port. In this case input and output
766operations are passed directly to the underlying port
767implementation without additional buffering. This is likely to
768slow down I/O operations. The buffering mode can be changed
769while a port is in use @pxref{Ports and File Descriptors,
770setvbuf}
771@item l
772Add line-buffering to the port. The port output buffer will be
773automatically flushed whenever a newline character is written.
c755b861
KR
774@item b
775Use binary mode. On DOS systems the default text mode converts CR+LF
776in the file to newline for the program, whereas binary mode reads and
777writes all bytes unchanged. On Unix-like systems there is no such
778distinction, text files already contain just newlines and no
779conversion is ever made. The @code{b} flag is accepted on all
780systems, 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}
784call, when that flag is available.)
07d83abe 785@end table
c755b861 786
092bdcc4
KR
787If a file cannot be opened with the access
788requested, @code{open-file} throws an exception.
789
07d83abe
MV
790In theory we could create read/write ports which were buffered
791in one direction only. However this isn't included in the
092bdcc4 792current interfaces.
07d83abe
MV
793@end deffn
794
795@rnindex open-input-file
796@deffn {Scheme Procedure} open-input-file filename
797Open @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
805Open @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
815Open @var{filename} for input or output, and call @code{(@var{proc}
816port)} 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
819cannot be opened.
820
821When @var{proc} returns, the port is closed. If @var{proc} does not
822return (eg.@: if it throws an error), then the port might not be
823closed automatically, though it will be garbage collected in the usual
824way 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
832Open @var{filename} and call @code{(@var{thunk})} with the new port
833setup as respectively the @code{current-input-port},
834@code{current-output-port}, or @code{current-error-port}. Return the
835value returned by @var{thunk}. @var{filename} is opened as per
836@code{open-input-file} or @code{open-output-file} respectively, and an
837error is signalled if it cannot be opened.
838
839When @var{thunk} returns, the port is closed and the previous setting
840of the respective current port is restored.
841
842The current port setting is managed with @code{dynamic-wind}, so the
843previous value is restored no matter how @var{thunk} exits (eg.@: an
844exception), and if @var{thunk} is re-entered (via a captured
845continuation) then it's set again to the @var{FILENAME} port.
846
847The port is closed when @var{thunk} returns normally, but not when
848exited via an exception or new continuation. This ensures it's still
849ready for use if @var{thunk} is re-entered by a captured continuation.
850Of course the port is always garbage collected and closed in the usual
851way when no longer referenced anywhere.
852@end deffn
853
854@deffn {Scheme Procedure} port-mode port
855@deffnx {C Function} scm_port_mode (port)
856Return the port modes associated with the open port @var{port}.
857These will not necessarily be identical to the modes used when
858the port was opened, since modes such as "append" which are
859used 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)
864Return the filename associated with @var{port}. This function returns
865the strings "standard input", "standard output" and "standard error"
866when called on the current input, output and error ports respectively.
e55abf41
KR
867
868@var{port} must be open, @code{port-filename} cannot be used once the
869port is closed.
07d83abe
MV
870@end deffn
871
872@deffn {Scheme Procedure} set-port-filename! port filename
873@deffnx {C Function} scm_set_port_filename_x (port, filename)
874Change the filename associated with @var{port}, using the current input
875port if none is specified. Note that this does not change the port's
876source 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)
882Determine 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
bf5df489
KR
888@cindex String port
889@cindex Port, string
07d83abe
MV
890
891The following allow string ports to be opened by analogy to R4R*
892file port facilities:
893
894@deffn {Scheme Procedure} call-with-output-string proc
895@deffnx {C Function} scm_call_with_output_string (proc)
896Calls the one-argument procedure @var{proc} with a newly created output
897port. When the function returns, the string composed of the characters
898written 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)
903Calls the one-argument procedure @var{proc} with a newly
904created input port from which @var{string}'s contents may be
905read. The value yielded by the @var{proc} is returned.
906@end deffn
907
908@deffn {Scheme Procedure} with-output-to-string thunk
909Calls the zero-argument procedure @var{thunk} with the current output
910port set temporarily to a new string port. It returns a string
911composed of the characters written to the current output.
912@end deffn
913
914@deffn {Scheme Procedure} with-input-from-string string thunk
915Calls the zero-argument procedure @var{thunk} with the current input
916port 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)
922Take a string and return an input port that delivers characters
923from the string. The port can be closed by
924@code{close-input-port}, though its storage will be reclaimed
925by 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 ()
930Return an output port that will accumulate characters for
931retrieval by @code{get-output-string}. The port can be closed
932by the procedure @code{close-output-port}, though its storage
933will be reclaimed by the garbage collector if it becomes
934inaccessible.
935@end deffn
936
937@deffn {Scheme Procedure} get-output-string port
938@deffnx {C Function} scm_get_output_string (port)
939Given an output port created by @code{open-output-string},
940return a string consisting of the characters that have been
941output to the port so far.
942
943@code{get-output-string} must be used before closing @var{port}, once
944closed the string cannot be obtained.
945@end deffn
946
947A string port can be used in many procedures which accept a port
948but which are not dependent on implementation details of fports.
949E.g., seeking and truncating will work on a string port,
950but trying to extract the file descriptor number will fail.
951
952
953@node Soft Ports
954@subsubsection Soft Ports
bf5df489
KR
955@cindex Soft port
956@cindex Port, soft
07d83abe
MV
957
958A @dfn{soft-port} is a port based on a vector of procedures capable of
959accepting 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)
963Return a port capable of receiving or delivering characters as
964specified by the @var{modes} string (@pxref{File Ports,
965open-file}). @var{pv} must be a vector of length 5 or 6. Its
966components are as follows:
967
968@enumerate 0
969@item
970procedure accepting one character for output
971@item
972procedure accepting a string for output
973@item
974thunk for flushing output
975@item
976thunk for getting one character
977@item
978thunk for closing port (not by garbage collection)
979@item
980(if present and not @code{#f}) thunk for computing the number of
981characters that can be read from the port without blocking.
982@end enumerate
983
984For an output-only port only elements 0, 1, 2, and 4 need be
985procedures. For an input-only port only elements 3 and 4 need
986be procedures. Thunks 2 and 4 can instead be @code{#f} if
987there is no useful operation for them to perform.
988
989If thunk 3 returns @code{#f} or an @code{eof-object}
990(@pxref{Input, eof-object?, ,r5rs, The Revised^5 Report on
991Scheme}) it indicates that the port has reached end-of-file.
992For 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
bf5df489
KR
1012@cindex Void port
1013@cindex Port, void
07d83abe
MV
1014
1015This kind of port causes any data to be discarded when written to, and
1016always 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)
1020Create and return a new void port. A void port acts like
1021@file{/dev/null}. The @var{mode} argument
1022specifies the input/output modes for this port: see the
1023documentation for @code{open-file} in @ref{File Ports}.
1024@end deffn
1025
1026
b242715b
LC
1027@node R6RS I/O Ports
1028@subsection R6RS I/O Ports
1029
1030@cindex R6RS
1031@cindex R6RS ports
1032
1033The I/O port API of the @uref{http://www.r6rs.org/, Revised Report^6 on
1034the Algorithmic Language Scheme (R6RS)} is provided by the @code{(rnrs
1035io ports)} module. It provides features, such as binary I/O and Unicode
1036string I/O, that complement or refine Guile's historical port API
1037presented 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
1041complete, 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
1056R5RS' @code{eof-object?} procedure is provided by the @code{(rnrs io
1057ports)} module:
1058
1059@deffn {Scheme Procedure} eof-object? obj
1060@deffnx {C Function} scm_eof_object_p (obj)
1061Return true if @var{obj} is the end-of-file (EOF) object.
1062@end deffn
1063
1064In addition, the following procedure is provided:
1065
1066@deffn {Scheme Procedure} eof-object
1067@deffnx {C Function} scm_eof_object ()
1068Return 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
1080The procedures listed below operate on any kind of R6RS I/O port.
1081
1082@deffn {Scheme Procedure} port-position port
1083If @var{port} supports it (see below), return the offset (an integer)
1084indicating where the next octet will be read from/written to in
1085@var{port}. If @var{port} does not support this operation, an error
1086condition is raised.
1087
1088This 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
1093Return @code{#t} is @var{port} supports @code{port-position}.
1094@end deffn
1095
1096@deffn {Scheme Procedure} set-port-position! port offset
1097If @var{port} supports it (see below), set the position where the next
1098octet will be read from/written to @var{port} to @var{offset} (an
1099integer). If @var{port} does not support this operation, an error
1100condition is raised.
1101
1102This 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
1107Return @code{#t} is @var{port} supports @code{set-port-position!}.
1108@end deffn
1109
1110@deffn {Scheme Procedure} call-with-port port proc
1111Call @var{proc}, passing it @var{port} and closing @var{port} upon exit
1112of @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
1121R6RS binary input ports can be created with the procedures described
1122below.
1123
1124@deffn {Scheme Procedure} open-bytevector-input-port bv [transcoder]
1125@deffnx {C Function} scm_open_bytevector_input_port (bv, transcoder)
1126Return an input port whose contents are drawn from bytevector @var{bv}
1127(@pxref{Bytevectors}).
1128
1129@c FIXME: Update description when implemented.
1130The @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)
1137Return a new custom binary input port@footnote{This is similar in spirit
1138to Guile's @dfn{soft ports} (@pxref{Soft Ports}).} named @var{id} (a
1139string) whose input is drained by invoking @var{read!} and passing it a
1140bytevector, an index where bytes should be written, and the number of
1141bytes to read. The @code{read!} procedure must return an integer
1142indicating the number of bytes read, or @code{0} to indicate the
1143end-of-file.
1144
1145Optionally, if @var{get-position} is not @code{#f}, it must be a thunk
1146that will be called when @var{port-position} is invoked on the custom
1147binary port and should return an integer indicating the position within
1148the underlying data stream; if @var{get-position} was not supplied, the
1149returned port does not support @var{port-position}.
1150
1151Likewise, if @var{set-position!} is not @code{#f}, it should be a
1152one-argument procedure. When @var{set-port-position!} is invoked on the
1153custom binary input port, @var{set-position!} is passed an integer
1154indicating the position of the next byte is to read.
1155
1156Finally, if @var{close} is not @code{#f}, it must be a thunk. It is
1157invoked when the custom binary input port is closed.
1158
1159Using a custom binary input port, the @code{open-bytevector-input-port}
1160procedure 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
1189Binary input is achieved using the procedures below:
1190
1191@deffn {Scheme Procedure} get-u8 port
1192@deffnx {C Function} scm_get_u8 (port)
1193Return an octet read from @var{port}, a binary input port, blocking as
1194necessary, 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)
1199Like @code{get-u8} but does not update @var{port}'s position to point
1200past 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)
1205Read @var{count} octets from @var{port}, blocking as necessary and
1206return a bytevector containing the octets read. If fewer bytes are
1207available, 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)
1212Read @var{count} bytes from @var{port} and store them in @var{bv}
1213starting at index @var{start}. Return either the number of bytes
1214actually 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)
1219Read from @var{port}, blocking as necessary, until data are available or
1220and end-of-file is reached. Return either a new bytevector containing
1221the 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)
1226Read from @var{port}, blocking as necessary, until the end-of-file is
1227reached. Return either a new bytevector containing the data read or the
1228end-of-file object (if no data were available).
1229@end deffn
1230
1231@node R6RS Binary Output
1232@subsubsection Binary Output
1233
1234Binary 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)
1238Return two values: a binary output port and a procedure. The latter
1239should be called with zero arguments to obtain a bytevector containing
1240the 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.
1254The @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)
1261Return a new custom binary output port named @var{id} (a string) whose
1262output is sunk by invoking @var{write!} and passing it a bytevector, an
1263index where bytes should be read from this bytevector, and the number of
1264bytes to be ``written''. The @code{write!} procedure must return an
1265integer indicating the number of bytes actually written; when it is
1266passed @code{0} as the number of bytes to write, it should behave as
1267though an end-of-file was sent to the byte sink.
1268
1269The 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
1274Writing to a binary output port can be done using the following
1275procedures:
1276
1277@deffn {Scheme Procedure} put-u8 port octet
1278@deffnx {C Function} scm_put_u8 (port, octet)
1279Write @var{octet}, an integer in the 0--255 range, to @var{port}, a
1280binary 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)
1285Write the contents of @var{bv} to @var{port}, optionally starting at
1286index @var{start} and limiting to @var{count} octets.
1287@end deffn
1288
1289
07d83abe
MV
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
bf5df489
KR
1301@cindex C port interface
1302@cindex Port, C interface
07d83abe
MV
1303
1304This section describes how to use Scheme ports from C.
1305
1306@subsubheading Port basics
1307
3081aee1
KR
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
07d83abe
MV
1314There are two main data structures. A port type object (ptob) is of
1315type @code{scm_ptob_descriptor}. A port instance is of type
1316@code{scm_port}. Given an @code{SCM} variable which points to a port,
1317the 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}
1320global array.
1321
1322@subsubheading Port buffers
1323
1324An input port always has a read buffer and an output port always has a
1325write buffer. However the size of these buffers is not guaranteed to be
1326more than one byte (e.g., the @code{shortbuf} field in @code{scm_port}
1327which is used when no other buffer is allocated). The way in which the
1328buffers are allocated depends on the implementation of the ptob. For
1329example in the case of an fport, buffers may be allocated with malloc
1330when the port is created, but in the case of an strport the underlying
1331string is used as the buffer.
1332
1333@subsubheading The @code{rw_random} flag
1334
1335Special treatment is required for ports which can be seeked at random.
1336Before various operations, such as seeking the port or changing from
1337input to output on a bidirectional port or vice versa, the port
1338implementation must be given a chance to update its state. The write
1339buffer is updated by calling the @code{flush} ptob procedure and the
1340input buffer is updated by calling the @code{end_input} ptob procedure.
1341In the case of an fport, @code{flush} causes buffered output to be
1342written to the file descriptor, while @code{end_input} causes the
1343descriptor position to be adjusted to account for buffered input which
1344was never read.
1345
1346The special treatment must be performed if the @code{rw_random} flag in
1347the port is non-zero.
1348
1349@subsubheading The @code{rw_active} variable
1350
1351The @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
1353values:
1354
1355@table @code
1356@item SCM_PORT_READ
1357the read buffer may have unread data.
1358
1359@item SCM_PORT_WRITE
1360the write buffer may have unwritten data.
1361
1362@item SCM_PORT_NEITHER
1363neither the write nor the read buffer has data.
1364@end table
1365
1366@subsubheading Reading from a port.
1367
1368To read from a port, it's possible to either call existing libguile
1369procedures such as @code{scm_getc} and @code{scm_read_line} or to read
1370data from the read buffer directly. Reading from the buffer involves
1371the following steps:
1372
1373@enumerate
1374@item
1375Flush output on the port, if @code{rw_active} is @code{SCM_PORT_WRITE}.
1376
1377@item
1378Fill 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
1381the 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
1390To write data to a port, calling @code{scm_lfwrite} should be sufficient for
1391most purposes. This takes care of the following steps:
1392
1393@enumerate
1394@item
1395End input on the port, if @code{rw_active} is @code{SCM_PORT_READ}.
1396
1397@item
1398Pass the data to the ptob implementation using the @code{write} ptob
1399procedure. The advantage of using the ptob @code{write} instead of
1400manipulating the write buffer directly is that it allows the data to be
1401written in one operation even if the port is using the single-byte
1402@code{shortbuf}.
1403
1404@item
1405Set @code{rw_active} to @code{SCM_PORT_WRITE} if @code{rw_random}
1406is set.
1407@end enumerate
1408
1409
1410@node Port Implementation
1411@subsubsection Port Implementation
bf5df489 1412@cindex Port implemenation
07d83abe
MV
1413
1414This section describes how to implement a new port type in C.
1415
1416As described in the previous section, a port type object (ptob) is
1417a structure of type @code{scm_ptob_descriptor}. A ptob is created by
1418calling @code{scm_make_port_type}.
1419
23f2b9a3
KR
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))
1421Return a new port type object. The @var{name}, @var{fill_input} and
1422@var{write} parameters are initial values for those port type fields,
1423as described below. The other fields are initialized with default
1424values and can be changed later.
1425@end deftypefun
1426
07d83abe
MV
1427All of the elements of the ptob, apart from @code{name}, are procedures
1428which collectively implement the port behaviour. Creating a new port
1429type mostly involves writing these procedures.
1430
07d83abe
MV
1431@table @code
1432@item name
1433A pointer to a NUL terminated string: the name of the port type. This
1434is the only element of @code{scm_ptob_descriptor} which is not
1435a procedure. Set via the first argument to @code{scm_make_port_type}.
1436
1437@item mark
1438Called during garbage collection to mark any SCM objects that a port
1439object may contain. It doesn't need to be set unless the port has
23f2b9a3
KR
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
07d83abe
MV
1444
1445@item free
1446Called when the port is collected during gc. It
1447should free any resources used by the port.
23f2b9a3
KR
1448Set using
1449
1450@deftypefun void scm_set_port_free (scm_t_bits tc, size_t (*free) (SCM port))
1451@end deftypefun
07d83abe
MV
1452
1453@item print
1454Called when @code{write} is called on the port object, to print a
23f2b9a3
KR
1455port 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))
1459The first argument @var{port} is the object being printed, the second
1460argument @var{dest_port} is where its description should go.
1461@end deftypefun
07d83abe
MV
1462
1463@item equalp
23f2b9a3
KR
1464Not used at present. Set using
1465
1466@deftypefun void scm_set_port_equalp (scm_t_bits tc, SCM (*equalp) (SCM, SCM))
1467@end deftypefun
07d83abe
MV
1468
1469@item close
1470Called when the port is closed, unless it was collected during gc. It
1471should free any resources used by the port.
23f2b9a3
KR
1472Set using
1473
1474@deftypefun void scm_set_port_close (scm_t_bits tc, int (*close) (SCM port))
1475@end deftypefun
07d83abe
MV
1476
1477@item write
1478Accept data which is to be written using the port. The port implementation
1479may choose to buffer the data instead of processing it directly.
1480Set via the third argument to @code{scm_make_port_type}.
1481
1482@item flush
1483Complete the processing of buffered output data. Reset the value of
1484@code{rw_active} to @code{SCM_PORT_NEITHER}.
23f2b9a3
KR
1485Set using
1486
1487@deftypefun void scm_set_port_flush (scm_t_bits tc, void (*flush) (SCM port))
1488@end deftypefun
07d83abe
MV
1489
1490@item end_input
1491Perform any synchronization required when switching from input to output
1492on the port. Reset the value of @code{rw_active} to @code{SCM_PORT_NEITHER}.
23f2b9a3
KR
1493Set using
1494
1495@deftypefun void scm_set_port_end_input (scm_t_bits tc, void (*end_input) (SCM port, int offset))
1496@end deftypefun
07d83abe
MV
1497
1498@item fill_input
1499Read new data into the read buffer and return the first character. It
1500can be assumed that the read buffer is empty when this procedure is called.
1501Set via the second argument to @code{scm_make_port_type}.
1502
1503@item input_waiting
1504Return a lower bound on the number of bytes that could be read from the
1505port without blocking. It can be assumed that the current state of
1506@code{rw_active} is @code{SCM_PORT_NEITHER}.
23f2b9a3
KR
1507Set using
1508
1509@deftypefun void scm_set_port_input_waiting (scm_t_bits tc, int (*input_waiting) (SCM port))
1510@end deftypefun
07d83abe
MV
1511
1512@item seek
1513Set the current position of the port. The procedure can not make
1514any assumptions about the value of @code{rw_active} when it's
1515called. It can reset the buffers first if desired by using something
1516like:
1517
1518@example
23f2b9a3
KR
1519if (pt->rw_active == SCM_PORT_READ)
1520 scm_end_input (port);
1521else if (pt->rw_active == SCM_PORT_WRITE)
1522 ptob->flush (port);
07d83abe
MV
1523@end example
1524
1525However note that this will have the side effect of discarding any data
1526in the unread-char buffer, in addition to any side effects from the
1527@code{end_input} and @code{flush} ptob procedures. This is undesirable
1528when 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
1530implementations take care to avoid this problem.
1531
23f2b9a3
KR
1532The procedure is set using
1533
f1ce9199 1534@deftypefun void scm_set_port_seek (scm_t_bits tc, scm_t_off (*seek) (SCM port, scm_t_off offset, int whence))
23f2b9a3 1535@end deftypefun
07d83abe
MV
1536
1537@item truncate
1538Truncate the port data to be specified length. It can be assumed that the
1539current state of @code{rw_active} is @code{SCM_PORT_NEITHER}.
23f2b9a3
KR
1540Set using
1541
f1ce9199 1542@deftypefun void scm_set_port_truncate (scm_t_bits tc, void (*truncate) (SCM port, scm_t_off length))
23f2b9a3 1543@end deftypefun
07d83abe
MV
1544
1545@end table
1546
1547
1548@c Local Variables:
1549@c TeX-master: "guile.texi"
1550@c End: