(Reading): Add scm_c_read.
[bpt/guile.git] / doc / ref / scheme-io.texi
CommitLineData
a0e07ba4
NJ
1@page
2@node Input and Output
3@chapter Input and Output
4
5@menu
6* Ports:: The idea of the port abstraction.
7* Reading:: Procedures for reading from a port.
8* Writing:: Procedures for writing to a port.
9* Closing:: Procedures to close a port.
10* Random Access:: Moving around a random access port.
11* Line/Delimited:: Read and write lines or delimited text.
12* Block Reading and Writing:: Reading and writing blocks of text.
13* Default Ports:: Defaults for input, output and errors.
14* Port Types:: Types of port and how to make them.
9401323e 15* I/O Extensions:: Using and extending ports in C.
a0e07ba4
NJ
16@end menu
17
18
19@node Ports
20@section Ports
21
a0e07ba4 22Sequential input/output in Scheme is represented by operations on a
7d5b2929
KR
23@dfn{port}. This chapter explains the operations that Guile provides
24for working with ports.
25
26Ports are created by opening, for instance @code{open-file} for a file
27(@pxref{File Ports}). Characters can be read from an input port and
28written to an output port, or both on an input/output port. A port
29can be closed (@pxref{Closing}) when no longer required, after which
30any attempt to read or write is an error.
a0e07ba4
NJ
31
32The formal definition of a port is very generic: an input port is
7d5b2929
KR
33simply ``an object which can deliver characters on demand,'' and an
34output port is ``an object which can accept characters.'' Because
35this definition is so loose, it is easy to write functions that
36simulate ports in software. @dfn{Soft ports} and @dfn{string ports}
37are two interesting and powerful examples of this technique.
38(@pxref{Soft Ports}, and @ref{String Ports}.)
39
40Ports are garbage collected in the usual way (@pxref{Memory
41Management}), and will be closed at that time if not already closed.
42In this case any errors occuring in the close will not be reported.
43Usually a program will want to explicitly close so as to be sure all
44its operations have been successful. Of course if a program has
45abandoned something due to an error or other condition then closing
46problems are probably not of interest.
47
48It is strongly recommended that file ports be closed explicitly when
49no longer required. Most systems have limits on how many files can be
50open, both on a per-process and a system-wide basis. A program that
51uses many files should take care not to hit those limits. The same
52applies to similar system resources such as pipes and sockets.
53
54Note that automatic garbage collection is triggered only by memory
55consumption, not by file or other resource usage, so a program cannot
56rely on that to keep it away from system limits. An explicit call to
57@code{gc} can of course be relied on to pick up unreferenced ports.
58If program flow makes it hard to be certain when to close then this
59may be an acceptable way to control resource usage.
a0e07ba4
NJ
60
61@rnindex input-port?
8f85c0c6
NJ
62@deffn {Scheme Procedure} input-port? x
63@deffnx {C Function} scm_input_port_p (x)
a0e07ba4
NJ
64Return @code{#t} if @var{x} is an input port, otherwise return
65@code{#f}. Any object satisfying this predicate also satisfies
66@code{port?}.
67@end deffn
68
69@rnindex output-port?
8f85c0c6
NJ
70@deffn {Scheme Procedure} output-port? x
71@deffnx {C Function} scm_output_port_p (x)
a0e07ba4
NJ
72Return @code{#t} if @var{x} is an output port, otherwise return
73@code{#f}. Any object satisfying this predicate also satisfies
74@code{port?}.
75@end deffn
76
8f85c0c6
NJ
77@deffn {Scheme Procedure} port? x
78@deffnx {C Function} scm_port_p (x)
a0e07ba4
NJ
79Return a boolean indicating whether @var{x} is a port.
80Equivalent to @code{(or (input-port? @var{x}) (output-port?
81@var{x}))}.
82@end deffn
83
84
85@node Reading
86@section Reading
87
88[Generic procedures for reading from ports.]
89
90@rnindex eof-object?
8f85c0c6
NJ
91@deffn {Scheme Procedure} eof-object? x
92@deffnx {C Function} scm_eof_object_p (x)
a0e07ba4
NJ
93Return @code{#t} if @var{x} is an end-of-file object; otherwise
94return @code{#f}.
95@end deffn
96
97@rnindex char-ready?
8f85c0c6
NJ
98@deffn {Scheme Procedure} char-ready? [port]
99@deffnx {C Function} scm_char_ready_p (port)
a0e07ba4
NJ
100Return @code{#t} if a character is ready on input @var{port}
101and return @code{#f} otherwise. If @code{char-ready?} returns
102@code{#t} then the next @code{read-char} operation on
103@var{port} is guaranteed not to hang. If @var{port} is a file
104port at end of file then @code{char-ready?} returns @code{#t}.
105@footnote{@code{char-ready?} exists to make it possible for a
106program to accept characters from interactive ports without
107getting stuck waiting for input. Any input editors associated
108with such ports must make sure that characters whose existence
109has been asserted by @code{char-ready?} cannot be rubbed out.
110If @code{char-ready?} were to return @code{#f} at end of file,
111a port at end of file would be indistinguishable from an
112interactive port that has no ready characters.}
113@end deffn
114
5a90a263 115@rnindex read-char
8f85c0c6
NJ
116@deffn {Scheme Procedure} read-char [port]
117@deffnx {C Function} scm_read_char (port)
a0e07ba4
NJ
118Return the next character available from @var{port}, updating
119@var{port} to point to the following character. If no more
120characters are available, the end-of-file object is returned.
121@end deffn
122
eee36f21
KR
123@deftypefn {C Function} size_t scm_c_read (SCM port, void *buffer, size_t size)
124Read up to @var{size} bytes from @var{port} and store them in
125@var{buffer}. The return value is the number of bytes actually read,
126which can be less than @var{size} if end-of-file has been reached.
127
128Note that this function does not update @code{port-line} and
129@code{port-column} below.
130@end deftypefn
131
5a90a263 132@rnindex peek-char
8f85c0c6
NJ
133@deffn {Scheme Procedure} peek-char [port]
134@deffnx {C Function} scm_peek_char (port)
a0e07ba4
NJ
135Return the next character available from @var{port},
136@emph{without} updating @var{port} to point to the following
137character. If no more characters are available, the
138end-of-file object is returned.@footnote{The value returned by
139a call to @code{peek-char} is the same as the value that would
140have been returned by a call to @code{read-char} on the same
141port. The only difference is that the very next call to
142@code{read-char} or @code{peek-char} on that @var{port} will
143return the value returned by the preceding call to
144@code{peek-char}. In particular, a call to @code{peek-char} on
145an interactive port will hang waiting for input whenever a call
146to @code{read-char} would have hung.}
147@end deffn
148
8f85c0c6
NJ
149@deffn {Scheme Procedure} unread-char cobj [port]
150@deffnx {C Function} scm_unread_char (cobj, port)
a0e07ba4
NJ
151Place @var{char} in @var{port} so that it will be read by the
152next read operation. If called multiple times, the unread characters
153will be read again in last-in first-out order. If @var{port} is
154not supplied, the current input port is used.
155@end deffn
156
8f85c0c6
NJ
157@deffn {Scheme Procedure} unread-string str port
158@deffnx {C Function} scm_unread_string (str, port)
fef68e7f
RB
159Place the string @var{str} in @var{port} so that its characters will
160be read from left-to-right as the next characters from @var{port}
161during subsequent read operations. If called multiple times, the
a0e07ba4
NJ
162unread characters will be read again in last-in first-out order. If
163@var{port} is not supplied, the current-input-port is used.
164@end deffn
165
8f85c0c6
NJ
166@deffn {Scheme Procedure} drain-input port
167@deffnx {C Function} scm_drain_input (port)
9401323e
NJ
168This procedure clears a port's input buffers, similar
169to the way that force-output clears the output buffer. The
170contents of the buffers are returned as a single string, e.g.,
171
172@lisp
173(define p (open-input-file ...))
174(drain-input p) => empty string, nothing buffered yet.
175(unread-char (read-char p) p)
176(drain-input p) => initial chars from p, up to the buffer size.
177@end lisp
178
179Draining the buffers may be useful for cleanly finishing
180buffered I/O so that the file descriptor can be used directly
181for further input.
a0e07ba4
NJ
182@end deffn
183
8f85c0c6
NJ
184@deffn {Scheme Procedure} port-column port
185@deffnx {Scheme Procedure} port-line port
186@deffnx {C Function} scm_port_column (port)
187@deffnx {C Function} scm_port_line (port)
eaa032c3
KR
188Return the current column number or line number of @var{port}.
189If the number is
a0e07ba4 190unknown, the result is #f. Otherwise, the result is a 0-origin integer
5a90a263 191- i.e.@: the first character of the first line is line 0, column 0.
a0e07ba4
NJ
192(However, when you display a file position, for example in an error
193message, we recommend you add 1 to get 1-origin integers. This is
194because lines and column numbers traditionally start with 1, and that is
195what non-programmers will find most natural.)
196@end deffn
197
8f85c0c6
NJ
198@deffn {Scheme Procedure} set-port-column! port column
199@deffnx {Scheme Procedure} set-port-line! port line
200@deffnx {C Function} scm_set_port_column_x (port, column)
201@deffnx {C Function} scm_set_port_line_x (port, line)
eaa032c3 202Set the current column or line number of @var{port}.
a0e07ba4
NJ
203@end deffn
204
205@node Writing
206@section Writing
207
208[Generic procedures for writing to ports.]
209
8f85c0c6
NJ
210@deffn {Scheme Procedure} get-print-state port
211@deffnx {C Function} scm_get_print_state (port)
5a90a263 212Return the print state of the port @var{port}. If @var{port}
a0e07ba4
NJ
213has no associated print state, @code{#f} is returned.
214@end deffn
215
bb6847e8
KR
216@rnindex write
217@deffn {Scheme Procedure} write obj [port]
218Send a representation of @var{obj} to @var{port} or to the current
219output port if not given.
220
221The output is designed to be machine readable, and can be read back
222with @code{read} (@pxref{Reading}). Strings are printed in
223doublequotes, with escapes if necessary, and characters are printed in
224@samp{#\} notation.
225@end deffn
226
9eb96786 227@rnindex display
8f85c0c6 228@deffn {Scheme Procedure} display obj [port]
bb6847e8
KR
229Send a representation of @var{obj} to @var{port} or to the current
230output port if not given.
231
232The output is designed for human readability, it differs from
233@code{write} in that strings are printed without doublequotes and
234escapes, and characters are printed as per @code{write-char}, not in
235@samp{#\} form.
9eb96786
TTN
236@end deffn
237
a0e07ba4 238@rnindex newline
8f85c0c6
NJ
239@deffn {Scheme Procedure} newline [port]
240@deffnx {C Function} scm_newline (port)
241Send a newline to @var{port}.
242If @var{port} is omitted, send to the current output port.
a0e07ba4
NJ
243@end deffn
244
8f85c0c6
NJ
245@deffn {Scheme Procedure} port-with-print-state port pstate
246@deffnx {C Function} scm_port_with_print_state (port, pstate)
a0e07ba4
NJ
247Create a new port which behaves like @var{port}, but with an
248included print state @var{pstate}.
249@end deffn
250
8f85c0c6
NJ
251@deffn {Scheme Procedure} print-options-interface [setting]
252@deffnx {C Function} scm_print_options (setting)
a0e07ba4
NJ
253Option interface for the print options. Instead of using
254this procedure directly, use the procedures
255@code{print-enable}, @code{print-disable}, @code{print-set!}
256and @code{print-options}.
257@end deffn
258
8f85c0c6
NJ
259@deffn {Scheme Procedure} simple-format destination message . args
260@deffnx {C Function} scm_simple_format (destination, message, args)
a0e07ba4
NJ
261Write @var{message} to @var{destination}, defaulting to
262the current output port.
263@var{message} can contain @code{~A} (was @code{%s}) and
264@code{~S} (was @code{%S}) escapes. When printed,
265the escapes are replaced with corresponding members of
266@var{ARGS}:
267@code{~A} formats using @code{display} and @code{~S} formats
268using @code{write}.
269If @var{destination} is @code{#t}, then use the current output
270port, if @var{destination} is @code{#f}, then return a string
271containing the formatted text. Does not add a trailing newline.
272@end deffn
273
274@rnindex write-char
8f85c0c6
NJ
275@deffn {Scheme Procedure} write-char chr [port]
276@deffnx {C Function} scm_write_char (chr, port)
a0e07ba4
NJ
277Send character @var{chr} to @var{port}.
278@end deffn
279
eee36f21
KR
280@deftypefn {C Function} void scm_c_write (SCM port, const void *buffer, size_t size)
281Write @var{size} bytes at @var{buffer} to @var{port}.
282
283Note that this function does not update @code{port-line} and
284@code{port-column} (@pxref{Reading}).
285@end deftypefn
286
a0e07ba4 287@findex fflush
8f85c0c6
NJ
288@deffn {Scheme Procedure} force-output [port]
289@deffnx {C Function} scm_force_output (port)
a0e07ba4
NJ
290Flush the specified output port, or the current output port if @var{port}
291is omitted. The current output buffer contents are passed to the
292underlying port implementation (e.g., in the case of fports, the
293data will be written to the file and the output buffer will be cleared.)
294It has no effect on an unbuffered port.
295
296The return value is unspecified.
297@end deffn
298
8f85c0c6
NJ
299@deffn {Scheme Procedure} flush-all-ports
300@deffnx {C Function} scm_flush_all_ports ()
a0e07ba4
NJ
301Equivalent to calling @code{force-output} on
302all open output ports. The return value is unspecified.
303@end deffn
304
305
306@node Closing
307@section Closing
308
8f85c0c6
NJ
309@deffn {Scheme Procedure} close-port port
310@deffnx {C Function} scm_close_port (port)
a0e07ba4
NJ
311Close the specified port object. Return @code{#t} if it
312successfully closes a port or @code{#f} if it was already
313closed. An exception may be raised if an error occurs, for
314example when flushing buffered output. See also @ref{Ports and
315File Descriptors, close}, for a procedure which can close file
316descriptors.
317@end deffn
318
8f85c0c6 319@deffn {Scheme Procedure} close-input-port port
2288712b 320@deffnx {Scheme Procedure} close-output-port port
8f85c0c6 321@deffnx {C Function} scm_close_input_port (port)
8f85c0c6 322@deffnx {C Function} scm_close_output_port (port)
2288712b
KR
323@rnindex close-input-port
324@rnindex close-output-port
325Close the specified input or output @var{port}. An exception may be
326raised if an error occurs while closing. If @var{port} is already
327closed, nothing is done. The return value is unspecified.
a0e07ba4
NJ
328
329See also @ref{Ports and File Descriptors, close}, for a procedure
330which can close file descriptors.
331@end deffn
332
8f85c0c6
NJ
333@deffn {Scheme Procedure} port-closed? port
334@deffnx {C Function} scm_port_closed_p (port)
a0e07ba4
NJ
335Return @code{#t} if @var{port} is closed or @code{#f} if it is
336open.
337@end deffn
338
339
340@node Random Access
341@section Random Access
342
8f85c0c6
NJ
343@deffn {Scheme Procedure} seek fd_port offset whence
344@deffnx {C Function} scm_seek (fd_port, offset, whence)
a0e07ba4
NJ
345Sets the current position of @var{fd/port} to the integer
346@var{offset}, which is interpreted according to the value of
347@var{whence}.
348
349One of the following variables should be supplied for
350@var{whence}:
351@defvar SEEK_SET
352Seek from the beginning of the file.
353@end defvar
354@defvar SEEK_CUR
355Seek from the current position.
356@end defvar
357@defvar SEEK_END
358Seek from the end of the file.
359@end defvar
360If @var{fd/port} is a file descriptor, the underlying system
361call is @code{lseek}. @var{port} may be a string port.
362
363The value returned is the new position in the file. This means
364that the current position of a port can be obtained using:
365@lisp
366(seek port 0 SEEK_CUR)
367@end lisp
368@end deffn
369
8f85c0c6
NJ
370@deffn {Scheme Procedure} ftell fd_port
371@deffnx {C Function} scm_ftell (fd_port)
a0e07ba4
NJ
372Return an integer representing the current position of
373@var{fd/port}, measured from the beginning. Equivalent to:
374
375@lisp
376(seek port 0 SEEK_CUR)
377@end lisp
378@end deffn
379
380@findex truncate
381@findex ftruncate
8f85c0c6
NJ
382@deffn {Scheme Procedure} truncate-file object [length]
383@deffnx {C Function} scm_truncate_file (object, length)
a0e07ba4
NJ
384Truncates the object referred to by @var{object} to at most
385@var{length} bytes. @var{object} can be a string containing a
386file name or an integer file descriptor or a port.
387@var{length} may be omitted if @var{object} is not a file name,
388in which case the truncation occurs at the current port.
389position. The return value is unspecified.
390@end deffn
391
392@node Line/Delimited
393@section Line Oriented and Delimited Text
394
395The delimited-I/O module can be accessed with:
396
397@smalllisp
398(use-modules (ice-9 rdelim))
399@end smalllisp
400
401It can be used to read or write lines of text, or read text delimited by
402a specified set of characters. It's similar to the @code{(scsh rdelim)}
403module from guile-scsh, but does not use multiple values or character
404sets and has an extra procedure @code{write-line}.
405
406@c begin (scm-doc-string "rdelim.scm" "read-line")
8f85c0c6 407@deffn {Scheme Procedure} read-line [port] [handle-delim]
a0e07ba4
NJ
408Return a line of text from @var{port} if specified, otherwise from the
409value returned by @code{(current-input-port)}. Under Unix, a line of text
410is terminated by the first end-of-line character or by end-of-file.
411
412If @var{handle-delim} is specified, it should be one of the following
413symbols:
414@table @code
415@item trim
416Discard the terminating delimiter. This is the default, but it will
417be impossible to tell whether the read terminated with a delimiter or
418end-of-file.
419@item concat
420Append the terminating delimiter (if any) to the returned string.
421@item peek
422Push the terminating delimiter (if any) back on to the port.
423@item split
424Return a pair containing the string read from the port and the
425terminating delimiter or end-of-file object.
426@end table
427@end deffn
428
429@c begin (scm-doc-string "rdelim.scm" "read-line!")
8f85c0c6 430@deffn {Scheme Procedure} read-line! buf [port]
a0e07ba4
NJ
431Read a line of text into the supplied string @var{buf} and return the
432number of characters added to @var{buf}. If @var{buf} is filled, then
433@code{#f} is returned.
434Read from @var{port} if
435specified, otherwise from the value returned by @code{(current-input-port)}.
436@end deffn
437
438@c begin (scm-doc-string "rdelim.scm" "read-delimited")
8f85c0c6 439@deffn {Scheme Procedure} read-delimited delims [port] [handle-delim]
a0e07ba4
NJ
440Read text until one of the characters in the string @var{delims} is found
441or end-of-file is reached. Read from @var{port} if supplied, otherwise
442from the value returned by @code{(current-input-port)}.
443@var{handle-delim} takes the same values as described for @code{read-line}.
444@end deffn
445
446@c begin (scm-doc-string "rdelim.scm" "read-delimited!")
8f85c0c6 447@deffn {Scheme Procedure} read-delimited! delims buf [port] [handle-delim] [start] [end]
a0e07ba4
NJ
448Read text into the supplied string @var{buf} and return the number of
449characters added to @var{buf} (subject to @var{handle-delim}, which takes
450the same values specified for @code{read-line}. If @var{buf} is filled,
451@code{#f} is returned for both the number of characters read and the
452delimiter. Also terminates if one of the characters in the string
453@var{delims} is found
454or end-of-file is reached. Read from @var{port} if supplied, otherwise
455from the value returned by @code{(current-input-port)}.
456@end deffn
457
8f85c0c6
NJ
458@deffn {Scheme Procedure} write-line obj [port]
459@deffnx {C Function} scm_write_line (obj, port)
a0e07ba4
NJ
460Display @var{obj} and a newline character to @var{port}. If
461@var{port} is not specified, @code{(current-output-port)} is
462used. This function is equivalent to:
463@lisp
464(display obj [port])
465(newline [port])
466@end lisp
467@end deffn
468
469Some of the abovementioned I/O functions rely on the following C
470primitives. These will mainly be of interest to people hacking Guile
471internals.
472
8f85c0c6
NJ
473@deffn {Scheme Procedure} %read-delimited! delims str gobble [port [start [end]]]
474@deffnx {C Function} scm_read_delimited_x (delims, str, gobble, port, start, end)
a0e07ba4
NJ
475Read characters from @var{port} into @var{str} until one of the
476characters in the @var{delims} string is encountered. If
477@var{gobble} is true, discard the delimiter character;
478otherwise, leave it in the input stream for the next read. If
479@var{port} is not specified, use the value of
480@code{(current-input-port)}. If @var{start} or @var{end} are
481specified, store data only into the substring of @var{str}
482bounded by @var{start} and @var{end} (which default to the
483beginning and end of the string, respectively).
484
485 Return a pair consisting of the delimiter that terminated the
486string and the number of characters read. If reading stopped
487at the end of file, the delimiter returned is the
488@var{eof-object}; if the string was filled without encountering
489a delimiter, this value is @code{#f}.
490@end deffn
491
8f85c0c6
NJ
492@deffn {Scheme Procedure} %read-line [port]
493@deffnx {C Function} scm_read_line (port)
a0e07ba4
NJ
494Read a newline-terminated line from @var{port}, allocating storage as
495necessary. The newline terminator (if any) is removed from the string,
496and a pair consisting of the line and its delimiter is returned. The
497delimiter may be either a newline or the @var{eof-object}; if
498@code{%read-line} is called at the end of file, it returns the pair
499@code{(#<eof> . #<eof>)}.
500@end deffn
501
502@node Block Reading and Writing
503@section Block reading and writing
504
505The Block-string-I/O module can be accessed with:
506
507@smalllisp
508(use-modules (ice-9 rw))
509@end smalllisp
510
511It currently contains procedures that help to implement the
512@code{(scsh rw)} module in guile-scsh.
513
8f85c0c6
NJ
514@deffn {Scheme Procedure} read-string!/partial str [port_or_fdes [start [end]]]
515@deffnx {C Function} scm_read_string_x_partial (str, port_or_fdes, start, end)
a0e07ba4
NJ
516Read characters from a port or file descriptor into a
517string @var{str}. A port must have an underlying file
518descriptor --- a so-called fport. This procedure is
519scsh-compatible and can efficiently read large strings.
520It will:
521
522@itemize
523@item
524attempt to fill the entire string, unless the @var{start}
525and/or @var{end} arguments are supplied. i.e., @var{start}
526defaults to 0 and @var{end} defaults to
527@code{(string-length str)}
528@item
529use the current input port if @var{port_or_fdes} is not
530supplied.
531@item
532return fewer than the requested number of characters in some
533cases, e.g., on end of file, if interrupted by a signal, or if
534not all the characters are immediately available.
535@item
536wait indefinitely for some input if no characters are
537currently available,
538unless the port is in non-blocking mode.
539@item
540read characters from the port's input buffers if available,
541instead from the underlying file descriptor.
542@item
543return @code{#f} if end-of-file is encountered before reading
544any characters, otherwise return the number of characters
545read.
546@item
547return 0 if the port is in non-blocking mode and no characters
548are immediately available.
549@item
550return 0 if the request is for 0 bytes, with no
551end-of-file check.
552@end itemize
553@end deffn
554
8f85c0c6
NJ
555@deffn {Scheme Procedure} write-string/partial str [port_or_fdes [start [end]]]
556@deffnx {C Function} scm_write_string_partial (str, port_or_fdes, start, end)
a0e07ba4
NJ
557Write characters from a string @var{str} to a port or file
558descriptor. A port must have an underlying file descriptor
559--- a so-called fport. This procedure is
560scsh-compatible and can efficiently write large strings.
561It will:
562
563@itemize
564@item
565attempt to write the entire string, unless the @var{start}
566and/or @var{end} arguments are supplied. i.e., @var{start}
567defaults to 0 and @var{end} defaults to
568@code{(string-length str)}
569@item
570use the current output port if @var{port_of_fdes} is not
571supplied.
572@item
573in the case of a buffered port, store the characters in the
574port's output buffer, if all will fit. If they will not fit
575then any existing buffered characters will be flushed
576before attempting
577to write the new characters directly to the underlying file
578descriptor. If the port is in non-blocking mode and
579buffered characters can not be flushed immediately, then an
580@code{EAGAIN} system-error exception will be raised (Note:
581scsh does not support the use of non-blocking buffered ports.)
582@item
583write fewer than the requested number of
584characters in some cases, e.g., if interrupted by a signal or
585if not all of the output can be accepted immediately.
586@item
587wait indefinitely for at least one character
588from @var{str} to be accepted by the port, unless the port is
589in non-blocking mode.
590@item
591return the number of characters accepted by the port.
592@item
593return 0 if the port is in non-blocking mode and can not accept
594at least one character from @var{str} immediately
595@item
596return 0 immediately if the request size is 0 bytes.
597@end itemize
598@end deffn
599
600@node Default Ports
601@section Default Ports for Input, Output and Errors
602
603@rnindex current-input-port
8f85c0c6
NJ
604@deffn {Scheme Procedure} current-input-port
605@deffnx {C Function} scm_current_input_port ()
a0e07ba4
NJ
606Return the current input port. This is the default port used
607by many input procedures. Initially, @code{current-input-port}
608returns the @dfn{standard input} in Unix and C terminology.
609@end deffn
610
611@rnindex current-output-port
8f85c0c6
NJ
612@deffn {Scheme Procedure} current-output-port
613@deffnx {C Function} scm_current_output_port ()
a0e07ba4
NJ
614Return the current output port. This is the default port used
615by many output procedures. Initially,
616@code{current-output-port} returns the @dfn{standard output} in
617Unix and C terminology.
618@end deffn
619
8f85c0c6
NJ
620@deffn {Scheme Procedure} current-error-port
621@deffnx {C Function} scm_current_error_port ()
a0e07ba4
NJ
622Return the port to which errors and warnings should be sent (the
623@dfn{standard error} in Unix and C terminology).
624@end deffn
625
8f85c0c6
NJ
626@deffn {Scheme Procedure} set-current-input-port port
627@deffnx {Scheme Procedure} set-current-output-port port
628@deffnx {Scheme Procedure} set-current-error-port port
629@deffnx {C Function} scm_set_current_input_port (port)
630@deffnx {C Function} scm_set_current_output_port (port)
631@deffnx {C Function} scm_set_current_error_port (port)
a0e07ba4
NJ
632Change the ports returned by @code{current-input-port},
633@code{current-output-port} and @code{current-error-port}, respectively,
634so that they use the supplied @var{port} for input or output.
635@end deffn
636
a0e07ba4
NJ
637
638@node Port Types
639@section Types of Port
640
641[Types of port; how to make them.]
642
643@menu
644* File Ports:: Ports on an operating system file.
645* String Ports:: Ports on a Scheme string.
646* Soft Ports:: Ports on arbitrary Scheme procedures.
647* Void Ports:: Ports on nothing at all.
648@end menu
649
650
651@node File Ports
652@subsection File Ports
653
654The following procedures are used to open file ports.
655See also @ref{Ports and File Descriptors, open}, for an interface
656to the Unix @code{open} system call.
657
7d5b2929
KR
658Most systems have limits on how many files can be open, so it's
659strongly recommended that file ports be closed explicitly when no
660longer required (@pxref{Ports}).
661
8f85c0c6
NJ
662@deffn {Scheme Procedure} open-file filename mode
663@deffnx {C Function} scm_open_file (filename, mode)
a0e07ba4
NJ
664Open the file whose name is @var{filename}, and return a port
665representing that file. The attributes of the port are
666determined by the @var{mode} string. The way in which this is
667interpreted is similar to C stdio. The first character must be
668one of the following:
669@table @samp
670@item r
671Open an existing file for input.
672@item w
673Open a file for output, creating it if it doesn't already exist
674or removing its contents if it does.
675@item a
676Open a file for output, creating it if it doesn't already
677exist. All writes to the port will go to the end of the file.
678The "append mode" can be turned off while the port is in use
679@pxref{Ports and File Descriptors, fcntl}
680@end table
681The following additional characters can be appended:
682@table @samp
683@item +
684Open the port for both input and output. E.g., @code{r+}: open
685an existing file for both input and output.
686@item 0
687Create an "unbuffered" port. In this case input and output
688operations are passed directly to the underlying port
689implementation without additional buffering. This is likely to
690slow down I/O operations. The buffering mode can be changed
691while a port is in use @pxref{Ports and File Descriptors,
692setvbuf}
693@item l
694Add line-buffering to the port. The port output buffer will be
695automatically flushed whenever a newline character is written.
696@end table
697In theory we could create read/write ports which were buffered
698in one direction only. However this isn't included in the
699current interfaces. If a file cannot be opened with the access
700requested, @code{open-file} throws an exception.
701@end deffn
702
703@rnindex open-input-file
8f85c0c6 704@deffn {Scheme Procedure} open-input-file filename
a0e07ba4
NJ
705Open @var{filename} for input. Equivalent to
706@smalllisp
707(open-file @var{filename} "r")
708@end smalllisp
709@end deffn
710
711@rnindex open-output-file
8f85c0c6 712@deffn {Scheme Procedure} open-output-file filename
a0e07ba4
NJ
713Open @var{filename} for output. Equivalent to
714@smalllisp
715(open-file @var{filename} "w")
716@end smalllisp
717@end deffn
718
2288712b
KR
719@deffn {Scheme Procedure} call-with-input-file filename proc
720@deffnx {Scheme Procedure} call-with-output-file filename proc
a0e07ba4 721@rnindex call-with-input-file
a0e07ba4 722@rnindex call-with-output-file
2288712b
KR
723Open @var{filename} for input or output, and call @code{(@var{proc}
724port)} with the resulting port. Return the value returned by
725@var{proc}. @var{filename} is opened as per @code{open-input-file} or
726@code{open-output-file} respectively, and an error is signalled if it
727cannot be opened.
a0e07ba4 728
2288712b
KR
729When @var{proc} returns, the port is closed. If @var{proc} does not
730return (eg.@: if it throws an error), then the port might not be
731closed automatically, though it will be garbage collected in the usual
732way if not otherwise referenced.
a0e07ba4
NJ
733@end deffn
734
2288712b
KR
735@deffn {Scheme Procedure} with-input-from-file filename thunk
736@deffnx {Scheme Procedure} with-output-to-file filename thunk
737@deffnx {Scheme Procedure} with-error-to-file filename thunk
738@rnindex with-input-from-file
a0e07ba4 739@rnindex with-output-to-file
2288712b
KR
740Open @var{filename} and call @code{(@var{thunk})} with the new port
741setup as respectively the @code{current-input-port},
742@code{current-output-port}, or @code{current-error-port}. Return the
743value returned by @var{thunk}. @var{filename} is opened as per
744@code{open-input-file} or @code{open-output-file} respectively, and an
745error is signalled if it cannot be opened.
746
747When @var{thunk} returns, the port is closed and the previous setting
748of the respective current port is restored.
749
750The current port setting is managed with @code{dynamic-wind}, so the
751previous value is restored no matter how @var{thunk} exits (eg.@: an
752exception), and if @var{thunk} is re-entered (via a captured
753continuation) then it's set again to the @var{FILENAME} port.
754
755The port is closed when @var{thunk} returns normally, but not when
756exited via an exception or new continuation. This ensures it's still
757ready for use if @var{thunk} is re-entered by a captured continuation.
758Of course the port is always garbage collected and closed in the usual
759way when no longer referenced anywhere.
a0e07ba4
NJ
760@end deffn
761
8f85c0c6
NJ
762@deffn {Scheme Procedure} port-mode port
763@deffnx {C Function} scm_port_mode (port)
764Return the port modes associated with the open port @var{port}.
765These will not necessarily be identical to the modes used when
766the port was opened, since modes such as "append" which are
767used only during port creation are not retained.
a0e07ba4
NJ
768@end deffn
769
8f85c0c6
NJ
770@deffn {Scheme Procedure} port-filename port
771@deffnx {C Function} scm_port_filename (port)
a0e07ba4
NJ
772Return the filename associated with @var{port}. This function returns
773the strings "standard input", "standard output" and "standard error"
774when called on the current input, output and error ports respectively.
775@end deffn
776
8f85c0c6
NJ
777@deffn {Scheme Procedure} set-port-filename! port filename
778@deffnx {C Function} scm_set_port_filename_x (port, filename)
a0e07ba4
NJ
779Change the filename associated with @var{port}, using the current input
780port if none is specified. Note that this does not change the port's
781source of data, but only the value that is returned by
782@code{port-filename} and reported in diagnostic output.
783@end deffn
784
8f85c0c6
NJ
785@deffn {Scheme Procedure} file-port? obj
786@deffnx {C Function} scm_file_port_p (obj)
a0e07ba4
NJ
787Determine whether @var{obj} is a port that is related to a file.
788@end deffn
789
790
791@node String Ports
792@subsection String Ports
793
794The following allow string ports to be opened by analogy to R4R*
795file port facilities:
796
8f85c0c6
NJ
797@deffn {Scheme Procedure} call-with-output-string proc
798@deffnx {C Function} scm_call_with_output_string (proc)
a0e07ba4
NJ
799Calls the one-argument procedure @var{proc} with a newly created output
800port. When the function returns, the string composed of the characters
801written into the port is returned.
802@end deffn
803
8f85c0c6
NJ
804@deffn {Scheme Procedure} call-with-input-string string proc
805@deffnx {C Function} scm_call_with_input_string (string, proc)
a0e07ba4
NJ
806Calls the one-argument procedure @var{proc} with a newly
807created input port from which @var{string}'s contents may be
808read. The value yielded by the @var{proc} is returned.
809@end deffn
810
8f85c0c6 811@deffn {Scheme Procedure} with-output-to-string thunk
a0e07ba4
NJ
812Calls the zero-argument procedure @var{thunk} with the current output
813port set temporarily to a new string port. It returns a string
814composed of the characters written to the current output.
815@end deffn
816
8f85c0c6 817@deffn {Scheme Procedure} with-input-from-string string thunk
a0e07ba4
NJ
818Calls the zero-argument procedure @var{thunk} with the current input
819port set temporarily to a string port opened on the specified
820@var{string}. The value yielded by @var{thunk} is returned.
821@end deffn
822
8f85c0c6
NJ
823@deffn {Scheme Procedure} open-input-string str
824@deffnx {C Function} scm_open_input_string (str)
a0e07ba4
NJ
825Take a string and return an input port that delivers characters
826from the string. The port can be closed by
827@code{close-input-port}, though its storage will be reclaimed
828by the garbage collector if it becomes inaccessible.
829@end deffn
830
8f85c0c6
NJ
831@deffn {Scheme Procedure} open-output-string
832@deffnx {C Function} scm_open_output_string ()
a0e07ba4
NJ
833Return an output port that will accumulate characters for
834retrieval by @code{get-output-string}. The port can be closed
835by the procedure @code{close-output-port}, though its storage
836will be reclaimed by the garbage collector if it becomes
837inaccessible.
838@end deffn
839
8f85c0c6
NJ
840@deffn {Scheme Procedure} get-output-string port
841@deffnx {C Function} scm_get_output_string (port)
a0e07ba4
NJ
842Given an output port created by @code{open-output-string},
843return a string consisting of the characters that have been
844output to the port so far.
845@end deffn
846
847A string port can be used in many procedures which accept a port
848but which are not dependent on implementation details of fports.
849E.g., seeking and truncating will work on a string port,
850but trying to extract the file descriptor number will fail.
851
852
853@node Soft Ports
854@subsection Soft Ports
855
856A @dfn{soft-port} is a port based on a vector of procedures capable of
857accepting or delivering characters. It allows emulation of I/O ports.
858
8f85c0c6
NJ
859@deffn {Scheme Procedure} make-soft-port pv modes
860@deffnx {C Function} scm_make_soft_port (pv, modes)
a0e07ba4
NJ
861Return a port capable of receiving or delivering characters as
862specified by the @var{modes} string (@pxref{File Ports,
0a50eeaa 863open-file}). @var{pv} must be a vector of length 5 or 6. Its
a0e07ba4
NJ
864components are as follows:
865
866@enumerate 0
867@item
868procedure accepting one character for output
869@item
870procedure accepting a string for output
871@item
872thunk for flushing output
873@item
874thunk for getting one character
875@item
876thunk for closing port (not by garbage collection)
0a50eeaa
NJ
877@item
878(if present and not @code{#f}) thunk for computing the number of
879characters that can be read from the port without blocking.
a0e07ba4
NJ
880@end enumerate
881
882For an output-only port only elements 0, 1, 2, and 4 need be
883procedures. For an input-only port only elements 3 and 4 need
884be procedures. Thunks 2 and 4 can instead be @code{#f} if
885there is no useful operation for them to perform.
886
887If thunk 3 returns @code{#f} or an @code{eof-object}
888(@pxref{Input, eof-object?, ,r5rs, The Revised^5 Report on
889Scheme}) it indicates that the port has reached end-of-file.
890For example:
891
892@lisp
893(define stdout (current-output-port))
894(define p (make-soft-port
895 (vector
896 (lambda (c) (write c stdout))
897 (lambda (s) (display s stdout))
898 (lambda () (display "." stdout))
899 (lambda () (char-upcase (read-char)))
900 (lambda () (display "@@" stdout)))
901 "rw"))
902
903(write p p) @result{} #<input-output: soft 8081e20>
904@end lisp
905@end deffn
906
907
908@node Void Ports
909@subsection Void Ports
910
911This kind of port causes any data to be discarded when written to, and
912always returns the end-of-file object when read from.
913
8f85c0c6
NJ
914@deffn {Scheme Procedure} %make-void-port mode
915@deffnx {C Function} scm_sys_make_void_port (mode)
a0e07ba4 916Create and return a new void port. A void port acts like
198586ed 917@file{/dev/null}. The @var{mode} argument
8f85c0c6
NJ
918specifies the input/output modes for this port: see the
919documentation for @code{open-file} in @ref{File Ports}.
a0e07ba4
NJ
920@end deffn
921
922
9401323e
NJ
923@node I/O Extensions
924@section Using and Extending Ports in C
925
926@menu
927* C Port Interface:: Using ports from C.
928* Port Implementation:: How to implement a new port type in C.
929@end menu
930
931
932@node C Port Interface
933@subsection C Port Interface
934
935This section describes how to use Scheme ports from C.
936
937@subsubsection Port basics
938
939There are two main data structures. A port type object (ptob) is of
940type @code{scm_ptob_descriptor}. A port instance is of type
941@code{scm_port}. Given an @code{SCM} variable which points to a port,
942the corresponding C port object can be obtained using the
943@code{SCM_PTAB_ENTRY} macro. The ptob can be obtained by using
944@code{SCM_PTOBNUM} to give an index into the @code{scm_ptobs}
945global array.
946
947@subsubsection Port buffers
948
949An input port always has a read buffer and an output port always has a
950write buffer. However the size of these buffers is not guaranteed to be
951more than one byte (e.g., the @code{shortbuf} field in @code{scm_port}
952which is used when no other buffer is allocated). The way in which the
953buffers are allocated depends on the implementation of the ptob. For
954example in the case of an fport, buffers may be allocated with malloc
955when the port is created, but in the case of an strport the underlying
956string is used as the buffer.
957
958@subsubsection The @code{rw_random} flag
959
960Special treatment is required for ports which can be seeked at random.
961Before various operations, such as seeking the port or changing from
962input to output on a bidirectional port or vice versa, the port
85a9b4ed 963implementation must be given a chance to update its state. The write
9401323e
NJ
964buffer is updated by calling the @code{flush} ptob procedure and the
965input buffer is updated by calling the @code{end_input} ptob procedure.
966In the case of an fport, @code{flush} causes buffered output to be
967written to the file descriptor, while @code{end_input} causes the
968descriptor position to be adjusted to account for buffered input which
969was never read.
970
971The special treatment must be performed if the @code{rw_random} flag in
972the port is non-zero.
973
974@subsubsection The @code{rw_active} variable
975
976The @code{rw_active} variable in the port is only used if
977@code{rw_random} is set. It's defined as an enum with the following
978values:
979
980@table @code
981@item SCM_PORT_READ
982the read buffer may have unread data.
983
984@item SCM_PORT_WRITE
985the write buffer may have unwritten data.
986
987@item SCM_PORT_NEITHER
988neither the write nor the read buffer has data.
989@end table
990
991@subsubsection Reading from a port.
992
993To read from a port, it's possible to either call existing libguile
994procedures such as @code{scm_getc} and @code{scm_read_line} or to read
995data from the read buffer directly. Reading from the buffer involves
996the following steps:
997
998@enumerate
999@item
1000Flush output on the port, if @code{rw_active} is @code{SCM_PORT_WRITE}.
1001
1002@item
1003Fill the read buffer, if it's empty, using @code{scm_fill_input}.
1004
1005@item Read the data from the buffer and update the read position in
1006the buffer. Steps 2) and 3) may be repeated as many times as required.
1007
1008@item Set rw_active to @code{SCM_PORT_READ} if @code{rw_random} is set.
1009
1010@item update the port's line and column counts.
1011@end enumerate
1012
1013@subsubsection Writing to a port.
1014
1015To write data to a port, calling @code{scm_lfwrite} should be sufficient for
1016most purposes. This takes care of the following steps:
1017
1018@enumerate
1019@item
1020End input on the port, if @code{rw_active} is @code{SCM_PORT_READ}.
1021
1022@item
1023Pass the data to the ptob implementation using the @code{write} ptob
1024procedure. The advantage of using the ptob @code{write} instead of
1025manipulating the write buffer directly is that it allows the data to be
1026written in one operation even if the port is using the single-byte
1027@code{shortbuf}.
1028
1029@item
1030Set @code{rw_active} to @code{SCM_PORT_WRITE} if @code{rw_random}
1031is set.
1032@end enumerate
1033
1034
1035@node Port Implementation
1036@subsection Port Implementation
1037
1038This section describes how to implement a new port type in C.
1039
1040As described in the previous section, a port type object (ptob) is
1041a structure of type @code{scm_ptob_descriptor}. A ptob is created by
1042calling @code{scm_make_port_type}.
1043
1044All of the elements of the ptob, apart from @code{name}, are procedures
1045which collectively implement the port behaviour. Creating a new port
1046type mostly involves writing these procedures.
1047
1048@code{scm_make_port_type} initializes three elements of the structure
1049(@code{name}, @code{fill_input} and @code{write}) from its arguments.
1050The remaining elements are initialized with default values and can be
1051set later if required.
1052
1053@table @code
1054@item name
1055A pointer to a NUL terminated string: the name of the port type. This
1056is the only element of @code{scm_ptob_descriptor} which is not
1057a procedure. Set via the first argument to @code{scm_make_port_type}.
1058
1059@item mark
1060Called during garbage collection to mark any SCM objects that a port
1061object may contain. It doesn't need to be set unless the port has
1062@code{SCM} components. Set using @code{scm_set_port_mark}.
1063
1064@item free
1065Called when the port is collected during gc. It
1066should free any resources used by the port.
1067Set using @code{scm_set_port_free}.
1068
1069@item print
1070Called when @code{write} is called on the port object, to print a
1071port description. e.g., for an fport it may produce something like:
1072@code{#<input: /etc/passwd 3>}. Set using @code{scm_set_port_print}.
1073
1074@item equalp
1075Not used at present. Set using @code{scm_set_port_equalp}.
1076
1077@item close
1078Called when the port is closed, unless it was collected during gc. It
1079should free any resources used by the port.
1080Set using @code{scm_set_port_close}.
1081
1082@item write
1083Accept data which is to be written using the port. The port implementation
1084may choose to buffer the data instead of processing it directly.
1085Set via the third argument to @code{scm_make_port_type}.
1086
1087@item flush
1088Complete the processing of buffered output data. Reset the value of
1089@code{rw_active} to @code{SCM_PORT_NEITHER}.
1090Set using @code{scm_set_port_flush}.
1091
1092@item end_input
85a9b4ed 1093Perform any synchronization required when switching from input to output
9401323e
NJ
1094on the port. Reset the value of @code{rw_active} to @code{SCM_PORT_NEITHER}.
1095Set using @code{scm_set_port_end_input}.
1096
1097@item fill_input
1098Read new data into the read buffer and return the first character. It
1099can be assumed that the read buffer is empty when this procedure is called.
1100Set via the second argument to @code{scm_make_port_type}.
1101
1102@item input_waiting
1103Return a lower bound on the number of bytes that could be read from the
1104port without blocking. It can be assumed that the current state of
1105@code{rw_active} is @code{SCM_PORT_NEITHER}.
1106Set using @code{scm_set_port_input_waiting}.
1107
1108@item seek
1109Set the current position of the port. The procedure can not make
1110any assumptions about the value of @code{rw_active} when it's
1111called. It can reset the buffers first if desired by using something
1112like:
1113
1114@example
1115 if (pt->rw_active == SCM_PORT_READ)
1116 scm_end_input (object);
1117 else if (pt->rw_active == SCM_PORT_WRITE)
1118 ptob->flush (object);
1119@end example
1120
1121However note that this will have the side effect of discarding any data
1122in the unread-char buffer, in addition to any side effects from the
1123@code{end_input} and @code{flush} ptob procedures. This is undesirable
1124when seek is called to measure the current position of the port, i.e.,
1125@code{(seek p 0 SEEK_CUR)}. The libguile fport and string port
1126implementations take care to avoid this problem.
1127
1128The procedure is set using @code{scm_set_port_seek}.
1129
1130@item truncate
1131Truncate the port data to be specified length. It can be assumed that the
1132current state of @code{rw_active} is @code{SCM_PORT_NEITHER}.
1133Set using @code{scm_set_port_truncate}.
1134
1135@end table
1136
1137
a0e07ba4
NJ
1138@c Local Variables:
1139@c TeX-master: "guile.texi"
1140@c End: