api-io.texi 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2009,
  4. @c 2010, 2011, 2013, 2016, 2019, 2021 Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Input and Output
  7. @section Input and Output
  8. @menu
  9. * Ports:: What's a port?
  10. * Binary I/O:: Reading and writing bytes.
  11. * Encoding:: Characters as bytes.
  12. * Textual I/O:: Reading and writing characters.
  13. * Simple Output:: Simple syntactic sugar solution.
  14. * Buffering:: Controlling when data is written to ports.
  15. * Random Access:: Moving around a random access port.
  16. * Line/Delimited:: Read and write lines or delimited text.
  17. * Default Ports:: Defaults for input, output and errors.
  18. * Port Types:: Types of port and how to make them.
  19. * Venerable Port Interfaces:: Procedures from the last millenium.
  20. * Using Ports from C:: Nice interfaces for C.
  21. * I/O Extensions:: Implementing new port types in C.
  22. * Non-Blocking I/O:: How Guile deals with EWOULDBLOCK.
  23. * BOM Handling:: Handling of Unicode byte order marks.
  24. @end menu
  25. @node Ports
  26. @subsection Ports
  27. @cindex Port
  28. Ports are the way that Guile performs input and output. Guile can read
  29. in characters or bytes from an @dfn{input port}, or write them out to an
  30. @dfn{output port}. Some ports support both interfaces.
  31. There are a number of different port types implemented in Guile. File
  32. ports provide input and output over files, as you might imagine. For
  33. example, we might display a string to a file like this:
  34. @example
  35. (let ((port (open-output-file "foo.txt")))
  36. (display "Hello, world!\n" port)
  37. (close-port port))
  38. @end example
  39. There are also string ports, for taking input from a string, or
  40. collecting output to a string; bytevector ports, for doing the same but
  41. using a bytevector as a source or sink of data; and soft ports, for
  42. arranging to call Scheme functions to provide input or handle output.
  43. @xref{Port Types}.
  44. Ports should be @dfn{closed} when they are not needed by calling
  45. @code{close-port} on them, as in the example above. This will make sure
  46. that any pending output is successfully written out to disk, in the case
  47. of a file port, or otherwise to whatever mutable store is backed by the
  48. port. Any error that occurs while writing out that buffered data would
  49. also be raised promptly at the @code{close-port}, and not later when the
  50. port is closed by the garbage collector. @xref{Buffering}, for more on
  51. buffered output.
  52. Closing a port also releases any precious resource the file might have.
  53. Usually in Scheme a programmer doesn't have to clean up after their data
  54. structures (@pxref{Memory Management}), but most systems have strict
  55. limits on how many files can be open, both on a per-process and a
  56. system-wide basis. A program that uses many files should take care not
  57. to hit those limits. The same applies to similar system resources such
  58. as pipes and sockets.
  59. Indeed for these reasons the above example is not the most idiomatic way
  60. to use ports. It is more common to acquire ports via procedures like
  61. @code{call-with-output-file}, which handle the @code{close-port}
  62. automatically:
  63. @example
  64. (call-with-output-file "foo.txt"
  65. (lambda (port)
  66. (display "Hello, world!\n" port)))
  67. @end example
  68. Finally, all ports have associated input and output buffers, as
  69. appropriate. Buffering is a common strategy to limit the overhead of
  70. small reads and writes: without buffering, each character fetched from a
  71. file would involve at least one call into the kernel, and maybe more
  72. depending on the character and the encoding. Instead, Guile will batch
  73. reads and writes into internal buffers. However, sometimes you want to
  74. make output on a port show up immediately. @xref{Buffering}, for more
  75. on interfaces to control port buffering.
  76. @deffn {Scheme Procedure} port? x
  77. @deffnx {C Function} scm_port_p (x)
  78. Return a boolean indicating whether @var{x} is a port.
  79. @end deffn
  80. @rnindex input-port?
  81. @deffn {Scheme Procedure} input-port? x
  82. @deffnx {C Function} scm_input_port_p (x)
  83. Return @code{#t} if @var{x} is an input port, otherwise return
  84. @code{#f}. Any object satisfying this predicate also satisfies
  85. @code{port?}.
  86. @end deffn
  87. @rnindex output-port?
  88. @deffn {Scheme Procedure} output-port? x
  89. @deffnx {C Function} scm_output_port_p (x)
  90. Return @code{#t} if @var{x} is an output port, otherwise return
  91. @code{#f}. Any object satisfying this predicate also satisfies
  92. @code{port?}.
  93. @end deffn
  94. @cindex Closing ports
  95. @cindex Port, close
  96. @deffn {Scheme Procedure} close-port port
  97. @deffnx {C Function} scm_close_port (port)
  98. Close the specified port object. Return @code{#t} if it successfully
  99. closes a port or @code{#f} if it was already closed. An exception may
  100. be raised if an error occurs, for example when flushing buffered output.
  101. @xref{Buffering}, for more on buffered output. @xref{Ports and File
  102. Descriptors, close}, for a procedure which can close file descriptors.
  103. @end deffn
  104. @deffn {Scheme Procedure} port-closed? port
  105. @deffnx {C Function} scm_port_closed_p (port)
  106. Return @code{#t} if @var{port} is closed or @code{#f} if it is
  107. open.
  108. @end deffn
  109. @deffn {Scheme Procedure} call-with-port port proc
  110. Call @var{proc}, passing it @var{port} and closing @var{port} upon exit
  111. of @var{proc}. Return the return values of @var{proc}.
  112. @end deffn
  113. @node Binary I/O
  114. @subsection Binary I/O
  115. Guile's ports are fundamentally binary in nature: at the lowest level,
  116. they work on bytes. This section describes Guile's core binary I/O
  117. operations. @xref{Textual I/O}, for input and output of strings and
  118. characters.
  119. To use these routines, first include the binary I/O module:
  120. @example
  121. (use-modules (ice-9 binary-ports))
  122. @end example
  123. Note that although this module's name suggests that binary ports are
  124. some different kind of port, that's not the case: all ports in Guile are
  125. both binary and textual ports.
  126. @cindex binary input
  127. @anchor{x-get-u8}
  128. @deffn {Scheme Procedure} get-u8 port
  129. @deffnx {C Function} scm_get_u8 (port)
  130. Return an octet read from @var{port}, an input port, blocking as
  131. necessary, or the end-of-file object.
  132. @end deffn
  133. @anchor{x-lookahead-u8}
  134. @deffn {Scheme Procedure} lookahead-u8 port
  135. @deffnx {C Function} scm_lookahead_u8 (port)
  136. Like @code{get-u8} but does not update @var{port}'s position to point
  137. past the octet.
  138. @end deffn
  139. The end-of-file object is unlike any other kind of object: it's not a
  140. pair, a symbol, or anything else. To check if a value is the
  141. end-of-file object, use the @code{eof-object?} predicate.
  142. @rnindex eof-object?
  143. @cindex End of file object
  144. @deffn {Scheme Procedure} eof-object? x
  145. @deffnx {C Function} scm_eof_object_p (x)
  146. Return @code{#t} if @var{x} is an end-of-file object, or @code{#f}
  147. otherwise.
  148. @end deffn
  149. Note that unlike other procedures in this module, @code{eof-object?} is
  150. defined in the default environment.
  151. @deffn {Scheme Procedure} get-bytevector-n port count
  152. @deffnx {C Function} scm_get_bytevector_n (port, count)
  153. Read @var{count} octets from @var{port}, blocking as necessary and
  154. return a bytevector containing the octets read. If fewer bytes are
  155. available, a bytevector smaller than @var{count} is returned.
  156. @end deffn
  157. @deffn {Scheme Procedure} get-bytevector-n! port bv start count
  158. @deffnx {C Function} scm_get_bytevector_n_x (port, bv, start, count)
  159. Read @var{count} bytes from @var{port} and store them in @var{bv}
  160. starting at index @var{start}. Return either the number of bytes
  161. actually read or the end-of-file object.
  162. @end deffn
  163. @deffn {Scheme Procedure} get-bytevector-some port
  164. @deffnx {C Function} scm_get_bytevector_some (port)
  165. Read from @var{port}, blocking as necessary, until bytes are available
  166. or an end-of-file is reached. Return either the end-of-file object or a
  167. new bytevector containing some of the available bytes (at least one),
  168. and update the port position to point just past these bytes.
  169. @end deffn
  170. @deffn {Scheme Procedure} get-bytevector-some! port bv start count
  171. @deffnx {C Function} scm_get_bytevector_some_x (port, bv, start, count)
  172. Read up to @var{count} bytes from @var{port}, blocking as necessary
  173. until at least one byte is available or an end-of-file is reached.
  174. Store them in @var{bv} starting at index @var{start}. Return the number
  175. of bytes actually read, or an end-of-file object.
  176. @end deffn
  177. @deffn {Scheme Procedure} get-bytevector-all port
  178. @deffnx {C Function} scm_get_bytevector_all (port)
  179. Read from @var{port}, blocking as necessary, until the end-of-file is
  180. reached. Return either a new bytevector containing the data read or the
  181. end-of-file object (if no data were available).
  182. @end deffn
  183. @deffn {Scheme Procedure} unget-bytevector port bv [start [count]]
  184. @deffnx {C Function} scm_unget_bytevector (port, bv, start, count)
  185. Place the contents of @var{bv} in @var{port}, optionally starting at
  186. index @var{start} and limiting to @var{count} octets, so that its bytes
  187. will be read from left-to-right as the next bytes from @var{port} during
  188. subsequent read operations. If called multiple times, the unread bytes
  189. will be read again in last-in first-out order.
  190. @end deffn
  191. @cindex binary output
  192. To perform binary output on a port, use @code{put-u8} or
  193. @code{put-bytevector}.
  194. @anchor{x-put-u8}
  195. @deffn {Scheme Procedure} put-u8 port octet
  196. @deffnx {C Function} scm_put_u8 (port, octet)
  197. Write @var{octet}, an integer in the 0--255 range, to @var{port}, a
  198. binary output port.
  199. @end deffn
  200. @deffn {Scheme Procedure} put-bytevector port bv [start [count]]
  201. @deffnx {C Function} scm_put_bytevector (port, bv, start, count)
  202. Write the contents of @var{bv} to @var{port}, optionally starting at
  203. index @var{start} and limiting to @var{count} octets.
  204. @end deffn
  205. @subsubheading Binary I/O in R7RS
  206. @ref{R7RS Standard Libraries,R7RS} defines the following binary I/O
  207. procedures. Access them with
  208. @example
  209. (use-modules (scheme base))
  210. @end example
  211. @anchor{x-open-output-bytevector}
  212. @deffn {Scheme Procedure} open-output-bytevector
  213. Returns a binary output port that will accumulate bytes
  214. for retrieval by @ref{x-get-output-bytevector,@code{get-output-bytevector}}.
  215. @end deffn
  216. @deffn {Scheme Procedure} write-u8 byte [out]
  217. Writes @var{byte} to the given binary output port @var{out} and returns
  218. an unspecified value. @var{out} defaults to @code{(current-output-port)}.
  219. See also @ref{x-put-u8,@code{put-u8}}.
  220. @end deffn
  221. @deffn {Scheme Procedure} read-u8 [in]
  222. Returns the next byte available from the binary input port @var{in},
  223. updating the port to point to the following byte. If no more bytes are
  224. available, an end-of-file object is returned. @var{in} defaults to
  225. @code{(current-input-port)}.
  226. See also @ref{x-get-u8,@code{get-u8}}.
  227. @end deffn
  228. @deffn {Scheme Procedure} peek-u8 [in]
  229. Returns the next byte available from the binary input port @var{in},
  230. but without updating the port to point to the following
  231. byte. If no more bytes are available, an end-of-file object
  232. is returned. @var{in} defaults to @code{(current-input-port)}.
  233. See also @ref{x-lookahead-u8,@code{lookahead-u8}}.
  234. @end deffn
  235. @anchor{x-get-output-bytevector}
  236. @deffn {Scheme Procedure} get-output-bytevector port
  237. Returns a bytevector consisting of the bytes that have been output to
  238. @var{port} so far in the order they were output. It is an error if
  239. @var{port} was not created with
  240. @ref{x-open-output-bytevector,@code{open-output-bytevector}}.
  241. @example
  242. (define out (open-output-bytevector))
  243. (write-u8 1 out)
  244. (write-u8 2 out)
  245. (write-u8 3 out)
  246. (get-output-bytevector out) @result{} #vu8(1 2 3)
  247. @end example
  248. @end deffn
  249. @deffn {Scheme Procedure} open-input-bytevector bv
  250. Takes a bytevector @var{bv} and returns a binary input port that
  251. delivers bytes from @var{bv}.
  252. @example
  253. (define in (open-input-bytevector #vu8(1 2 3)))
  254. (read-u8 in) @result{} 1
  255. (peek-u8 in) @result{} 2
  256. (read-u8 in) @result{} 2
  257. (read-u8 in) @result{} 3
  258. (read-u8 in) @result{} #<eof>
  259. @end example
  260. @end deffn
  261. @deffn {Scheme Procedure} read-bytevector! bv [port [start [end]]]
  262. Reads the next @var{end} - @var{start} bytes, or as many as are
  263. available before the end of file, from the binary input port into the
  264. bytevector @var{bv} in left-to-right order beginning at the @var{start}
  265. position. If @var{end} is not supplied, reads until the end of @var{bv}
  266. has been reached. If @var{start} is not supplied, reads beginning at
  267. position 0.
  268. Returns the number of bytes read. If no bytes are available, an
  269. end-of-file object is returned.
  270. @example
  271. (define in (open-input-bytevector #vu8(1 2 3)))
  272. (define bv (make-bytevector 5 0))
  273. (read-bytevector! bv in 1 3) @result{} 2
  274. bv @result{} #vu8(0 1 2 0 0 0)
  275. @end example
  276. @end deffn
  277. @deffn {Scheme Procedure} read-bytevector k in
  278. Reads the next @var{k} bytes, or as many as are available before the end
  279. of file if that is less than @var{k}, from the binary input port
  280. @var{in} into a newly allocated bytevector in left-to-right order, and
  281. returns the bytevector. If no bytes are available before the end of
  282. file, an end-of-file object is returned.
  283. @example
  284. (define bv #vu8(1 2 3))
  285. (read-bytevector 2 (open-input-bytevector bv)) @result{} #vu8(1 2)
  286. (read-bytevector 10 (open-input-bytevector bv)) @result{} #vu8(1 2 3)
  287. @end example
  288. @end deffn
  289. @deffn {Scheme Procedure} write-bytevector bv [port [start [end]]]
  290. Writes the bytes of bytevector @var{bv} from @var{start} to @var{end} in
  291. left-to-right order to the binary output @var{port}. @var{start}
  292. defaults to 0 and @var{end} defaults to the length of @var{bv}.
  293. @example
  294. (define out (open-output-bytevector))
  295. (write-bytevector #vu8(0 1 2 3 4) out 2 4)
  296. (get-output-bytevector out) @result{} #vu8(2 3)
  297. @end example
  298. @end deffn
  299. @node Encoding
  300. @subsection Encoding
  301. Textual input and output on Guile ports is layered on top of binary
  302. operations. To this end, each port has an associated character encoding
  303. that controls how bytes read from the port are converted to characters,
  304. and how characters written to the port are converted to bytes.
  305. @deffn {Scheme Procedure} port-encoding port
  306. @deffnx {C Function} scm_port_encoding (port)
  307. Returns, as a string, the character encoding that @var{port} uses to
  308. interpret its input and output.
  309. @end deffn
  310. @deffn {Scheme Procedure} set-port-encoding! port enc
  311. @deffnx {C Function} scm_set_port_encoding_x (port, enc)
  312. Sets the character encoding that will be used to interpret I/O to
  313. @var{port}. @var{enc} is a string containing the name of an encoding.
  314. Valid encoding names are those
  315. @url{http://www.iana.org/assignments/character-sets, defined by IANA},
  316. for example @code{"UTF-8"} or @code{"ISO-8859-1"}.
  317. @end deffn
  318. When ports are created, they are assigned an encoding. The usual
  319. process to determine the initial encoding for a port is to take the
  320. value of the @code{%default-port-encoding} fluid.
  321. @defvr {Scheme Variable} %default-port-encoding
  322. A fluid containing name of the encoding to be used by default for newly
  323. created ports (@pxref{Fluids and Dynamic States}). As a special case,
  324. the value @code{#f} is equivalent to @code{"ISO-8859-1"}.
  325. @end defvr
  326. The @code{%default-port-encoding} itself defaults to the encoding
  327. appropriate for the current locale, if @code{setlocale} has been called.
  328. @xref{Locales}, for more on locales and when you might need to call
  329. @code{setlocale} explicitly.
  330. Some port types have other ways of determining their initial locales.
  331. String ports, for example, default to the UTF-8 encoding, in order to be
  332. able to represent all characters regardless of the current locale. File
  333. ports can optionally sniff their file for a @code{coding:} declaration;
  334. @xref{File Ports}. Binary ports might be initialized to the ISO-8859-1
  335. encoding in which each codepoint between 0 and 255 corresponds to a byte
  336. with that value.
  337. Currently, the ports only work with @emph{non-modal} encodings. Most
  338. encodings are non-modal, meaning that the conversion of bytes to a
  339. string doesn't depend on its context: the same byte sequence will always
  340. return the same string. A couple of modal encodings are in common use,
  341. like ISO-2022-JP and ISO-2022-KR, and they are not yet supported.
  342. @cindex port conversion strategy
  343. @cindex conversion strategy, port
  344. @cindex decoding error
  345. @cindex encoding error
  346. Each port also has an associated conversion strategy, which determines
  347. what to do when a Guile character can't be converted to the port's
  348. encoded character representation for output. There are three possible
  349. strategies: to raise an error, to replace the character with a hex
  350. escape, or to replace the character with a substitute character. Port
  351. conversion strategies are also used when decoding characters from an
  352. input port.
  353. @deffn {Scheme Procedure} port-conversion-strategy port
  354. @deffnx {C Function} scm_port_conversion_strategy (port)
  355. Returns the behavior of the port when outputting a character that is not
  356. representable in the port's current encoding.
  357. If @var{port} is @code{#f}, then the current default behavior will be
  358. returned. New ports will have this default behavior when they are
  359. created.
  360. @end deffn
  361. @deffn {Scheme Procedure} set-port-conversion-strategy! port sym
  362. @deffnx {C Function} scm_set_port_conversion_strategy_x (port, sym)
  363. Sets the behavior of Guile when outputting a character that is not
  364. representable in the port's current encoding, or when Guile encounters a
  365. decoding error when trying to read a character. @var{sym} can be either
  366. @code{error}, @code{substitute}, or @code{escape}.
  367. If @var{port} is an open port, the conversion error behavior is set for
  368. that port. If it is @code{#f}, it is set as the default behavior for
  369. any future ports that get created in this thread.
  370. @end deffn
  371. As with port encodings, there is a fluid which determines the initial
  372. conversion strategy for a port.
  373. @deffn {Scheme Variable} %default-port-conversion-strategy
  374. The fluid that defines the conversion strategy for newly created ports,
  375. and also for other conversion routines such as @code{scm_to_stringn},
  376. @code{scm_from_stringn}, @code{string->pointer}, and
  377. @code{pointer->string}.
  378. Its value must be one of the symbols described above, with the same
  379. semantics: @code{error}, @code{substitute}, or @code{escape}.
  380. When Guile starts, its value is @code{substitute}.
  381. Note that @code{(set-port-conversion-strategy! #f @var{sym})} is
  382. equivalent to @code{(fluid-set! %default-port-conversion-strategy
  383. @var{sym})}.
  384. @end deffn
  385. As mentioned above, for an output port there are three possible port
  386. conversion strategies. The @code{error} strategy will throw an error
  387. when a nonconvertible character is encountered. The @code{substitute}
  388. strategy will replace nonconvertible characters with a question mark
  389. (@samp{?}). Finally the @code{escape} strategy will print
  390. nonconvertible characters as a hex escape, using the escaping that is
  391. recognized by Guile's string syntax. Note that if the port's encoding
  392. is a Unicode encoding, like @code{UTF-8}, then encoding errors are
  393. impossible.
  394. For an input port, the @code{error} strategy will cause Guile to throw
  395. an error if it encounters an invalid encoding, such as might happen if
  396. you tried to read @code{ISO-8859-1} as @code{UTF-8}. The error is
  397. thrown before advancing the read position. The @code{substitute}
  398. strategy will replace the bad bytes with a U+FFFD replacement character,
  399. in accordance with Unicode recommendations. When reading from an input
  400. port, the @code{escape} strategy is treated as if it were @code{error}.
  401. @node Textual I/O
  402. @subsection Textual I/O
  403. @cindex textual input
  404. @cindex textual output
  405. This section describes Guile's core textual I/O operations on characters
  406. and strings. @xref{Binary I/O}, for input and output of bytes and
  407. bytevectors. @xref{Encoding}, for more on how characters relate to
  408. bytes. To read general S-expressions from ports, @xref{Scheme Read}.
  409. @xref{Scheme Write}, for interfaces that write generic Scheme datums.
  410. To use these routines, first include the textual I/O module:
  411. @example
  412. (use-modules (ice-9 textual-ports))
  413. @end example
  414. Note that although this module's name suggests that textual ports are
  415. some different kind of port, that's not the case: all ports in Guile are
  416. both binary and textual ports.
  417. @deffn {Scheme Procedure} get-char input-port
  418. Reads from @var{input-port}, blocking as necessary, until a
  419. complete character is available from @var{input-port},
  420. or until an end of file is reached.
  421. If a complete character is available before the next end of file,
  422. @code{get-char} returns that character and updates the input port to
  423. point past the character. If an end of file is reached before any
  424. character is read, @code{get-char} returns the end-of-file object.
  425. @end deffn
  426. @deffn {Scheme Procedure} lookahead-char input-port
  427. The @code{lookahead-char} procedure is like @code{get-char}, but it does
  428. not update @var{input-port} to point past the character.
  429. @end deffn
  430. In the same way that it's possible to "unget" a byte or bytes, it's
  431. possible to "unget" the bytes corresponding to an encoded character.
  432. @deffn {Scheme Procedure} unget-char port char
  433. Place character @var{char} in @var{port} so that it will be read by the
  434. next read operation. If called multiple times, the unread characters
  435. will be read again in last-in first-out order.
  436. @end deffn
  437. @deffn {Scheme Procedure} unget-string port str
  438. Place the string @var{str} in @var{port} so that its characters will
  439. be read from left-to-right as the next characters from @var{port}
  440. during subsequent read operations. If called multiple times, the
  441. unread characters will be read again in last-in first-out order.
  442. @end deffn
  443. Reading in a character at a time can be inefficient. If it's possible
  444. to perform I/O over multiple characters at a time, via strings, that
  445. might be faster.
  446. @deffn {Scheme Procedure} get-string-n input-port count
  447. The @code{get-string-n} procedure reads from @var{input-port}, blocking
  448. as necessary, until @var{count} characters are available, or until an
  449. end of file is reached. @var{count} must be an exact, non-negative
  450. integer, representing the number of characters to be read.
  451. If @var{count} characters are available before end of file,
  452. @code{get-string-n} returns a string consisting of those @var{count}
  453. characters. If fewer characters are available before an end of file, but
  454. one or more characters can be read, @code{get-string-n} returns a string
  455. containing those characters. In either case, the input port is updated
  456. to point just past the characters read. If no characters can be read
  457. before an end of file, the end-of-file object is returned.
  458. @end deffn
  459. @deffn {Scheme Procedure} get-string-n! input-port string start count
  460. The @code{get-string-n!} procedure reads from @var{input-port} in the
  461. same manner as @code{get-string-n}. @var{start} and @var{count} must be
  462. exact, non-negative integer objects, with @var{count} representing the
  463. number of characters to be read. @var{string} must be a string with at
  464. least $@var{start} + @var{count}$ characters.
  465. If @var{count} characters are available before an end of file, they are
  466. written into @var{string} starting at index @var{start}, and @var{count}
  467. is returned. If fewer characters are available before an end of file,
  468. but one or more can be read, those characters are written into
  469. @var{string} starting at index @var{start} and the number of characters
  470. actually read is returned as an exact integer object. If no characters
  471. can be read before an end of file, the end-of-file object is returned.
  472. @end deffn
  473. @deffn {Scheme Procedure} get-string-all input-port
  474. Reads from @var{input-port} until an end of file, decoding characters in
  475. the same manner as @code{get-string-n} and @code{get-string-n!}.
  476. If characters are available before the end of file, a string containing
  477. all the characters decoded from that data are returned. If no character
  478. precedes the end of file, the end-of-file object is returned.
  479. @end deffn
  480. @deffn {Scheme Procedure} get-line input-port
  481. Reads from @var{input-port} up to and including the linefeed
  482. character or end of file, decoding characters in the same manner as
  483. @code{get-string-n} and @code{get-string-n!}.
  484. If a linefeed character is read, a string containing all of the text up
  485. to (but not including) the linefeed character is returned, and the port
  486. is updated to point just past the linefeed character. If an end of file
  487. is encountered before any linefeed character is read, but some
  488. characters have been read and decoded as characters, a string containing
  489. those characters is returned. If an end of file is encountered before
  490. any characters are read, the end-of-file object is returned.
  491. @end deffn
  492. Finally, there are just two core procedures to write characters to a
  493. port.
  494. @deffn {Scheme Procedure} put-char port char
  495. Writes @var{char} to the port. The @code{put-char} procedure returns
  496. an unspecified value.
  497. @end deffn
  498. @deffn {Scheme Procedure} put-string port string
  499. @deffnx {Scheme Procedure} put-string port string start
  500. @deffnx {Scheme Procedure} put-string port string start count
  501. Write the @var{count} characters of @var{string} starting at index
  502. @var{start} to the port.
  503. @var{start} and @var{count} must be non-negative exact integer objects.
  504. @var{string} must have a length of at least @math{@var{start} +
  505. @var{count}}. @var{start} defaults to 0. @var{count} defaults to
  506. @math{@code{(string-length @var{string})} - @var{start}}$.
  507. Calling @code{put-string} is equivalent in all respects to calling
  508. @code{put-char} on the relevant sequence of characters, except that it
  509. will attempt to write multiple characters to the port at a time, even if
  510. the port is unbuffered.
  511. The @code{put-string} procedure returns an unspecified value.
  512. @end deffn
  513. Textual ports have a textual position associated with them: a line and a
  514. column. Reading in characters or writing them out advances the line and
  515. the column appropriately.
  516. @deffn {Scheme Procedure} port-column port
  517. @deffnx {Scheme Procedure} port-line port
  518. @deffnx {C Function} scm_port_column (port)
  519. @deffnx {C Function} scm_port_line (port)
  520. Return the current column number or line number of @var{port}.
  521. @end deffn
  522. Port lines and positions are represented as 0-origin integers, which is
  523. to say that the the first character of the first line is line 0, column
  524. 0. However, when you display a line number, for example in an error
  525. message, we recommend you add 1 to get 1-origin integers. This is
  526. because lines numbers traditionally start with 1, and that is what
  527. non-programmers will find most natural.
  528. @deffn {Scheme Procedure} set-port-column! port column
  529. @deffnx {Scheme Procedure} set-port-line! port line
  530. @deffnx {C Function} scm_set_port_column_x (port, column)
  531. @deffnx {C Function} scm_set_port_line_x (port, line)
  532. Set the current column or line number of @var{port}.
  533. @end deffn
  534. @node Simple Output
  535. @subsection Simple Textual Output
  536. Guile exports a simple formatted output function, @code{simple-format}.
  537. For a more capable formatted output facility, @xref{Formatted Output}.
  538. @deffn {Scheme Procedure} simple-format destination message . args
  539. @deffnx {C Function} scm_simple_format (destination, message, args)
  540. Write @var{message} to @var{destination}, defaulting to the current
  541. output port. @var{message} can contain @code{~A} and @code{~S} escapes.
  542. When printed, the escapes are replaced with corresponding members of
  543. @var{args}: @code{~A} formats using @code{display} and @code{~S} formats
  544. using @code{write}. If @var{destination} is @code{#t}, then use the
  545. current output port, if @var{destination} is @code{#f}, then return a
  546. string containing the formatted text. Does not add a trailing newline.
  547. @end deffn
  548. Somewhat confusingly, Guile binds the @code{format} identifier to
  549. @code{simple-format} at startup. Once @code{(ice-9 format)} loads, it
  550. actually replaces the core @code{format} binding, so depending on
  551. whether you or a module you use has loaded @code{(ice-9 format)}, you
  552. may be using the simple or the more capable version.
  553. @node Buffering
  554. @subsection Buffering
  555. @cindex Port, buffering
  556. Every port has associated input and output buffers. You can think of
  557. ports as being backed by some mutable store, and that store might be far
  558. away. For example, ports backed by file descriptors have to go all the
  559. way to the kernel to read and write their data. To avoid this
  560. round-trip cost, Guile usually reads in data from the mutable store in
  561. chunks, and then services small requests like @code{get-char} out of
  562. that intermediate buffer. Similarly, small writes like
  563. @code{write-char} first go to a buffer, and are sent to the store when
  564. the buffer is full (or when port is flushed). Buffered ports speed up
  565. your program by reducing the number of round-trips to the mutable store,
  566. and they do so in a way that is mostly transparent to the user.
  567. There are two major ways, however, in which buffering affects program
  568. semantics. Building correct, performant programs requires understanding
  569. these situations.
  570. The first case is in random-access read/write ports (@pxref{Random
  571. Access}). These ports, usually backed by a file, logically operate over
  572. the same mutable store when both reading and writing. So, if you read a
  573. character, causing the buffer to fill, then write a character, the bytes
  574. you filled in your read buffer are now invalid. Every time you switch
  575. between reading and writing, Guile has to flush any pending buffer. If
  576. this happens frequently, the cost can be high. In that case you should
  577. reduce the amount that you buffer, in both directions. Similarly, Guile
  578. has to flush buffers before seeking. None of these considerations apply
  579. to sockets, which don't logically read from and write to the same
  580. mutable store, and are not seekable. Note also that sockets are
  581. unbuffered by default. @xref{Network Sockets and Communication}.
  582. The second case is the more pernicious one. If you write data to a
  583. buffered port, it probably doesn't go out to the mutable store directly.
  584. (This ``probably'' introduces some indeterminism in your program: what
  585. goes to the store, and when, depends on how full the buffer is. It is
  586. something that the user needs to explicitly be aware of.) The data is
  587. written to the store later -- when the buffer fills up due to another
  588. write, or when @code{force-output} is called, or when @code{close-port}
  589. is called, or when the program exits, or even when the garbage collector
  590. runs. The salient point is, @emph{the errors are signalled then too}.
  591. Buffered writes defer error detection (and defer the side effects to the
  592. mutable store), perhaps indefinitely if the port type does not need to
  593. be closed at GC.
  594. One common heuristic that works well for textual ports is to flush
  595. output when a newline (@code{\n}) is written. This @dfn{line buffering}
  596. mode is on by default for TTY ports. Most other ports are @dfn{block
  597. buffered}, meaning that once the output buffer reaches the block size,
  598. which depends on the port and its configuration, the output is flushed
  599. as a block, without regard to what is in the block. Likewise reads are
  600. read in at the block size, though if there are fewer bytes available to
  601. read, the buffer may not be entirely filled.
  602. Note that binary reads or writes that are larger than the buffer size go
  603. directly to the mutable store without passing through the buffers. If
  604. your access pattern involves many big reads or writes, buffering might
  605. not matter so much to you.
  606. To control the buffering behavior of a port, use @code{setvbuf}.
  607. @deffn {Scheme Procedure} setvbuf port mode [size]
  608. @deffnx {C Function} scm_setvbuf (port, mode, size)
  609. @cindex port buffering
  610. Set the buffering mode for @var{port}. @var{mode} can be one of the
  611. following symbols:
  612. @table @code
  613. @item none
  614. non-buffered
  615. @item line
  616. line buffered
  617. @item block
  618. block buffered, using a newly allocated buffer of @var{size} bytes.
  619. If @var{size} is omitted, a default size will be used.
  620. @end table
  621. @end deffn
  622. Another way to set the buffering, for file ports, is to open the file
  623. with @code{0} or @code{l} as part of the mode string, for unbuffered or
  624. line-buffered ports, respectively. @xref{File Ports}, for more.
  625. Any buffered output data will be written out when the port is closed.
  626. To make sure to flush it at specific points in your program, use
  627. @code{force-otput}.
  628. @findex fflush
  629. @deffn {Scheme Procedure} force-output [port]
  630. @deffnx {C Function} scm_force_output (port)
  631. Flush the specified output port, or the current output port if
  632. @var{port} is omitted. The current output buffer contents, if any, are
  633. passed to the underlying port implementation.
  634. The return value is unspecified.
  635. @end deffn
  636. @deffn {Scheme Procedure} flush-all-ports
  637. @deffnx {C Function} scm_flush_all_ports ()
  638. Equivalent to calling @code{force-output} on all open output ports. The
  639. return value is unspecified.
  640. @end deffn
  641. Similarly, sometimes you might want to switch from using Guile's ports
  642. to working directly on file descriptors. In that case, for input ports
  643. use @code{drain-input} to get any buffered input from that port.
  644. @deffn {Scheme Procedure} drain-input port
  645. @deffnx {C Function} scm_drain_input (port)
  646. This procedure clears a port's input buffers, similar
  647. to the way that force-output clears the output buffer. The
  648. contents of the buffers are returned as a single string, e.g.,
  649. @lisp
  650. (define p (open-input-file ...))
  651. (drain-input p) => empty string, nothing buffered yet.
  652. (unread-char (read-char p) p)
  653. (drain-input p) => initial chars from p, up to the buffer size.
  654. @end lisp
  655. @end deffn
  656. All of these considerations are very similar to those of streams in the
  657. C library, although Guile's ports are not built on top of C streams.
  658. Still, it is useful to read what other systems do.
  659. @xref{Streams,,,libc,The GNU C Library Reference Manual}, for more
  660. discussion on C streams.
  661. @node Random Access
  662. @subsection Random Access
  663. @cindex Random access, ports
  664. @cindex Port, random access
  665. @deffn {Scheme Procedure} seek fd_port offset whence
  666. @deffnx {C Function} scm_seek (fd_port, offset, whence)
  667. Sets the current position of @var{fd_port} to the integer
  668. @var{offset}. For a file port, @var{offset} is expressed
  669. as a number of bytes; for other types of ports, such as string
  670. ports, @var{offset} is an abstract representation of the
  671. position within the port's data, not necessarily expressed
  672. as a number of bytes. @var{offset} is interpreted according to
  673. the value of @var{whence}.
  674. One of the following variables should be supplied for
  675. @var{whence}:
  676. @defvar SEEK_SET
  677. Seek from the beginning of the file.
  678. @end defvar
  679. @defvar SEEK_CUR
  680. Seek from the current position.
  681. @end defvar
  682. @defvar SEEK_END
  683. Seek from the end of the file.
  684. @end defvar
  685. If @var{fd_port} is a file descriptor, the underlying system
  686. call is @code{lseek}. @var{port} may be a string port.
  687. The value returned is the new position in @var{fd_port}. This means
  688. that the current position of a port can be obtained using:
  689. @lisp
  690. (seek port 0 SEEK_CUR)
  691. @end lisp
  692. @end deffn
  693. @deffn {Scheme Procedure} ftell fd_port
  694. @deffnx {C Function} scm_ftell (fd_port)
  695. Return an integer representing the current position of
  696. @var{fd_port}, measured from the beginning. Equivalent to:
  697. @lisp
  698. (seek port 0 SEEK_CUR)
  699. @end lisp
  700. @end deffn
  701. @findex truncate
  702. @findex ftruncate
  703. @deffn {Scheme Procedure} truncate-file file [length]
  704. @deffnx {C Function} scm_truncate_file (file, length)
  705. Truncate @var{file} to @var{length} bytes. @var{file} can be a
  706. filename string, a port object, or an integer file descriptor. The
  707. return value is unspecified.
  708. For a port or file descriptor @var{length} can be omitted, in which
  709. case the file is truncated at the current position (per @code{ftell}
  710. above).
  711. On most systems a file can be extended by giving a length greater than
  712. the current size, but this is not mandatory in the POSIX standard.
  713. @end deffn
  714. @node Line/Delimited
  715. @subsection Line Oriented and Delimited Text
  716. @cindex Line input/output
  717. @cindex Port, line input/output
  718. The delimited-I/O module can be accessed with:
  719. @lisp
  720. (use-modules (ice-9 rdelim))
  721. @end lisp
  722. It can be used to read or write lines of text, or read text delimited by
  723. a specified set of characters.
  724. @deffn {Scheme Procedure} read-line [port] [handle-delim]
  725. Return a line of text from @var{port} if specified, otherwise from the
  726. value returned by @code{(current-input-port)}. Under Unix, a line of text
  727. is terminated by the first end-of-line character or by end-of-file.
  728. If @var{handle-delim} is specified, it should be one of the following
  729. symbols:
  730. @table @code
  731. @item trim
  732. Discard the terminating delimiter. This is the default, but it will
  733. be impossible to tell whether the read terminated with a delimiter or
  734. end-of-file.
  735. @item concat
  736. Append the terminating delimiter (if any) to the returned string.
  737. @item peek
  738. Push the terminating delimiter (if any) back on to the port.
  739. @item split
  740. Return a pair containing the string read from the port and the
  741. terminating delimiter or end-of-file object.
  742. @end table
  743. @end deffn
  744. @deffn {Scheme Procedure} read-line! buf [port]
  745. Read a line of text into the supplied string @var{buf} and return the
  746. number of characters added to @var{buf}. If @var{buf} is filled, then
  747. @code{#f} is returned. Read from @var{port} if specified, otherwise
  748. from the value returned by @code{(current-input-port)}.
  749. @end deffn
  750. @deffn {Scheme Procedure} read-delimited delims [port] [handle-delim]
  751. Read text until one of the characters in the string @var{delims} is
  752. found or end-of-file is reached. Read from @var{port} if supplied,
  753. otherwise from the value returned by @code{(current-input-port)}.
  754. @var{handle-delim} takes the same values as described for
  755. @code{read-line}.
  756. @end deffn
  757. @c begin (scm-doc-string "rdelim.scm" "read-delimited!")
  758. @deffn {Scheme Procedure} read-delimited! delims buf [port] [handle-delim] [start] [end]
  759. Read text into the supplied string @var{buf}.
  760. If a delimiter was found, return the number of characters written,
  761. except if @var{handle-delim} is @code{split}, in which case the return
  762. value is a pair, as noted above.
  763. As a special case, if @var{port} was already at end-of-stream, the EOF
  764. object is returned. Also, if no characters were written because the
  765. buffer was full, @code{#f} is returned.
  766. It's something of a wacky interface, to be honest.
  767. @end deffn
  768. @deffn {Scheme Procedure} %read-delimited! delims str gobble [port [start [end]]]
  769. @deffnx {C Function} scm_read_delimited_x (delims, str, gobble, port, start, end)
  770. Read characters from @var{port} into @var{str} until one of the
  771. characters in the @var{delims} string is encountered. If
  772. @var{gobble} is true, discard the delimiter character;
  773. otherwise, leave it in the input stream for the next read. If
  774. @var{port} is not specified, use the value of
  775. @code{(current-input-port)}. If @var{start} or @var{end} are
  776. specified, store data only into the substring of @var{str}
  777. bounded by @var{start} and @var{end} (which default to the
  778. beginning and end of the string, respectively).
  779. Return a pair consisting of the delimiter that terminated the
  780. string and the number of characters read. If reading stopped
  781. at the end of file, the delimiter returned is the
  782. @var{eof-object}; if the string was filled without encountering
  783. a delimiter, this value is @code{#f}.
  784. @end deffn
  785. @deffn {Scheme Procedure} %read-line [port]
  786. @deffnx {C Function} scm_read_line (port)
  787. Read a newline-terminated line from @var{port}, allocating storage as
  788. necessary. The newline terminator (if any) is removed from the string,
  789. and a pair consisting of the line and its delimiter is returned. The
  790. delimiter may be either a newline or the @var{eof-object}; if
  791. @code{%read-line} is called at the end of file, it returns the pair
  792. @code{(#<eof> . #<eof>)}.
  793. @end deffn
  794. @deffn {Scheme Procedure} write-line obj [port]
  795. @deffnx {C Function} scm_write_line (obj, port)
  796. Display @var{obj} and a newline character to @var{port}. If
  797. @var{port} is not specified, @code{(current-output-port)} is
  798. used. This procedure is equivalent to:
  799. @lisp
  800. (display obj [port])
  801. (newline [port])
  802. @end lisp
  803. @end deffn
  804. @node Default Ports
  805. @subsection Default Ports for Input, Output and Errors
  806. @cindex Default ports
  807. @cindex Port, default
  808. @rnindex current-input-port
  809. @deffn {Scheme Procedure} current-input-port
  810. @deffnx {C Function} scm_current_input_port ()
  811. @cindex standard input
  812. Return the current input port. This is the default port used
  813. by many input procedures.
  814. Initially this is the @dfn{standard input} in Unix and C terminology.
  815. When the standard input is a tty the port is unbuffered, otherwise
  816. it's fully buffered.
  817. Unbuffered input is good if an application runs an interactive
  818. subprocess, since any type-ahead input won't go into Guile's buffer
  819. and be unavailable to the subprocess.
  820. Note that Guile buffering is completely separate from the tty ``line
  821. discipline''. In the usual cooked mode on a tty Guile only sees a
  822. line of input once the user presses @key{Return}.
  823. @end deffn
  824. @rnindex current-output-port
  825. @deffn {Scheme Procedure} current-output-port
  826. @deffnx {C Function} scm_current_output_port ()
  827. @cindex standard output
  828. Return the current output port. This is the default port used
  829. by many output procedures.
  830. Initially this is the @dfn{standard output} in Unix and C terminology.
  831. When the standard output is a tty this port is unbuffered, otherwise
  832. it's fully buffered.
  833. Unbuffered output to a tty is good for ensuring progress output or a
  834. prompt is seen. But an application which always prints whole lines
  835. could change to line buffered, or an application with a lot of output
  836. could go fully buffered and perhaps make explicit @code{force-output}
  837. calls (@pxref{Buffering}) at selected points.
  838. @end deffn
  839. @deffn {Scheme Procedure} current-error-port
  840. @deffnx {C Function} scm_current_error_port ()
  841. @cindex standard error output
  842. Return the port to which errors and warnings should be sent.
  843. Initially this is the @dfn{standard error} in Unix and C terminology.
  844. When the standard error is a tty this port is unbuffered, otherwise
  845. it's fully buffered.
  846. @end deffn
  847. @deffn {Scheme Procedure} set-current-input-port port
  848. @deffnx {Scheme Procedure} set-current-output-port port
  849. @deffnx {Scheme Procedure} set-current-error-port port
  850. @deffnx {C Function} scm_set_current_input_port (port)
  851. @deffnx {C Function} scm_set_current_output_port (port)
  852. @deffnx {C Function} scm_set_current_error_port (port)
  853. Change the ports returned by @code{current-input-port},
  854. @code{current-output-port} and @code{current-error-port}, respectively,
  855. so that they use the supplied @var{port} for input or output.
  856. @end deffn
  857. @deffn {Scheme Procedure} with-input-from-port port thunk
  858. @deffnx {Scheme Procedure} with-output-to-port port thunk
  859. @deffnx {Scheme Procedure} with-error-to-port port thunk
  860. Call @var{thunk} in a dynamic environment in which
  861. @code{current-input-port}, @code{current-output-port} or
  862. @code{current-error-port} is rebound to the given @var{port}.
  863. @end deffn
  864. @deftypefn {C Function} void scm_dynwind_current_input_port (SCM port)
  865. @deftypefnx {C Function} void scm_dynwind_current_output_port (SCM port)
  866. @deftypefnx {C Function} void scm_dynwind_current_error_port (SCM port)
  867. These functions must be used inside a pair of calls to
  868. @code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
  869. Wind}). During the dynwind context, the indicated port is set to
  870. @var{port}.
  871. More precisely, the current port is swapped with a `backup' value
  872. whenever the dynwind context is entered or left. The backup value is
  873. initialized with the @var{port} argument.
  874. @end deftypefn
  875. @node Port Types
  876. @subsection Types of Port
  877. @cindex Types of ports
  878. @cindex Port, types
  879. @menu
  880. * File Ports:: Ports on an operating system file.
  881. * Bytevector Ports:: Ports on a bytevector.
  882. * String Ports:: Ports on a Scheme string.
  883. * Custom Ports:: Ports whose implementation you control.
  884. * Soft Ports:: An older version of custom ports.
  885. * Void Ports:: Ports on nothing at all.
  886. @end menu
  887. @node File Ports
  888. @subsubsection File Ports
  889. @cindex File port
  890. @cindex Port, file
  891. The following procedures are used to open file ports.
  892. See also @ref{Ports and File Descriptors, open}, for an interface
  893. to the Unix @code{open} system call.
  894. All file access uses the ``LFS'' large file support functions when
  895. available, so files bigger than 2 Gbytes (@math{2^31} bytes) can be
  896. read and written on a 32-bit system.
  897. Most systems have limits on how many files can be open, so it's
  898. strongly recommended that file ports be closed explicitly when no
  899. longer required (@pxref{Ports}).
  900. @deffn {Scheme Procedure} open-file filename mode @
  901. [#:guess-encoding=#f] [#:encoding=#f]
  902. @deffnx {C Function} scm_open_file_with_encoding @
  903. (filename, mode, guess_encoding, encoding)
  904. @deffnx {C Function} scm_open_file (filename, mode)
  905. Open the file whose name is @var{filename}, and return a port
  906. representing that file. The attributes of the port are
  907. determined by the @var{mode} string. The way in which this is
  908. interpreted is similar to C stdio. The first character must be
  909. one of the following:
  910. @table @samp
  911. @item r
  912. Open an existing file for input.
  913. @item w
  914. Open a file for output, creating it if it doesn't already exist
  915. or removing its contents if it does.
  916. @item a
  917. Open a file for output, creating it if it doesn't already
  918. exist. All writes to the port will go to the end of the file.
  919. The "append mode" can be turned off while the port is in use
  920. @pxref{Ports and File Descriptors, fcntl}
  921. @end table
  922. The following additional characters can be appended:
  923. @table @samp
  924. @item b
  925. Open the underlying file in binary mode, if supported by the system.
  926. Also, open the file using the binary-compatible character encoding
  927. "ISO-8859-1", ignoring the default port encoding.
  928. @item +
  929. Open the port for both input and output. E.g., @code{r+}: open
  930. an existing file for both input and output.
  931. @item e
  932. Mark the underlying file descriptor as close-on-exec, as per the
  933. @code{O_CLOEXEC} flag.
  934. @item 0
  935. Create an "unbuffered" port. In this case input and output
  936. operations are passed directly to the underlying port
  937. implementation without additional buffering. This is likely to
  938. slow down I/O operations. The buffering mode can be changed
  939. while a port is in use (@pxref{Buffering}).
  940. @item l
  941. Add line-buffering to the port. The port output buffer will be
  942. automatically flushed whenever a newline character is written.
  943. @item b
  944. Use binary mode, ensuring that each byte in the file will be read as one
  945. Scheme character.
  946. To provide this property, the file will be opened with the 8-bit
  947. character encoding "ISO-8859-1", ignoring the default port encoding.
  948. @xref{Ports}, for more information on port encodings.
  949. Note that while it is possible to read and write binary data as
  950. characters or strings, it is usually better to treat bytes as octets,
  951. and byte sequences as bytevectors. @xref{Binary I/O}, for more.
  952. This option had another historical meaning, for DOS compatibility: in
  953. the default (textual) mode, DOS reads a CR-LF sequence as one LF byte.
  954. The @code{b} flag prevents this from happening, adding @code{O_BINARY}
  955. to the underlying @code{open} call. Still, the flag is generally useful
  956. because of its port encoding ramifications.
  957. @end table
  958. Unless binary mode is requested, the character encoding of the new port
  959. is determined as follows: First, if @var{guess-encoding} is true, the
  960. @code{file-encoding} procedure is used to guess the encoding of the file
  961. (@pxref{Character Encoding of Source Files}). If @var{guess-encoding}
  962. is false or if @code{file-encoding} fails, @var{encoding} is used unless
  963. it is also false. As a last resort, the default port encoding is used.
  964. @xref{Ports}, for more information on port encodings. It is an error to
  965. pass a non-false @var{guess-encoding} or @var{encoding} if binary mode
  966. is requested.
  967. If a file cannot be opened with the access requested, @code{open-file}
  968. throws an exception.
  969. @end deffn
  970. @rnindex open-input-file
  971. @deffn {Scheme Procedure} open-input-file filename @
  972. [#:guess-encoding=#f] [#:encoding=#f] [#:binary=#f]
  973. Open @var{filename} for input. If @var{binary} is true, open the port
  974. in binary mode, otherwise use text mode. @var{encoding} and
  975. @var{guess-encoding} determine the character encoding as described above
  976. for @code{open-file}. Equivalent to
  977. @lisp
  978. (open-file @var{filename}
  979. (if @var{binary} "rb" "r")
  980. #:guess-encoding @var{guess-encoding}
  981. #:encoding @var{encoding})
  982. @end lisp
  983. @end deffn
  984. @rnindex open-output-file
  985. @deffn {Scheme Procedure} open-output-file filename @
  986. [#:encoding=#f] [#:binary=#f]
  987. Open @var{filename} for output. If @var{binary} is true, open the port
  988. in binary mode, otherwise use text mode. @var{encoding} specifies the
  989. character encoding as described above for @code{open-file}. Equivalent
  990. to
  991. @lisp
  992. (open-file @var{filename}
  993. (if @var{binary} "wb" "w")
  994. #:encoding @var{encoding})
  995. @end lisp
  996. @end deffn
  997. @deffn {Scheme Procedure} call-with-input-file filename proc @
  998. [#:guess-encoding=#f] [#:encoding=#f] [#:binary=#f]
  999. @deffnx {Scheme Procedure} call-with-output-file filename proc @
  1000. [#:encoding=#f] [#:binary=#f]
  1001. @rnindex call-with-input-file
  1002. @rnindex call-with-output-file
  1003. Open @var{filename} for input or output, and call @code{(@var{proc}
  1004. port)} with the resulting port. Return the value returned by
  1005. @var{proc}. @var{filename} is opened as per @code{open-input-file} or
  1006. @code{open-output-file} respectively, and an error is signaled if it
  1007. cannot be opened.
  1008. When @var{proc} returns, the port is closed. If @var{proc} does not
  1009. return (e.g.@: if it throws an error), then the port might not be
  1010. closed automatically, though it will be garbage collected in the usual
  1011. way if not otherwise referenced.
  1012. @end deffn
  1013. @deffn {Scheme Procedure} with-input-from-file filename thunk @
  1014. [#:guess-encoding=#f] [#:encoding=#f] [#:binary=#f]
  1015. @deffnx {Scheme Procedure} with-output-to-file filename thunk @
  1016. [#:encoding=#f] [#:binary=#f]
  1017. @deffnx {Scheme Procedure} with-error-to-file filename thunk @
  1018. [#:encoding=#f] [#:binary=#f]
  1019. @rnindex with-input-from-file
  1020. @rnindex with-output-to-file
  1021. Open @var{filename} and call @code{(@var{thunk})} with the new port
  1022. setup as respectively the @code{current-input-port},
  1023. @code{current-output-port}, or @code{current-error-port}. Return the
  1024. value returned by @var{thunk}. @var{filename} is opened as per
  1025. @code{open-input-file} or @code{open-output-file} respectively, and an
  1026. error is signaled if it cannot be opened.
  1027. When @var{thunk} returns, the port is closed and the previous setting
  1028. of the respective current port is restored.
  1029. The current port setting is managed with @code{dynamic-wind}, so the
  1030. previous value is restored no matter how @var{thunk} exits (eg.@: an
  1031. exception), and if @var{thunk} is re-entered (via a captured
  1032. continuation) then it's set again to the @var{filename} port.
  1033. The port is closed when @var{thunk} returns normally, but not when
  1034. exited via an exception or new continuation. This ensures it's still
  1035. ready for use if @var{thunk} is re-entered by a captured continuation.
  1036. Of course the port is always garbage collected and closed in the usual
  1037. way when no longer referenced anywhere.
  1038. @end deffn
  1039. @deffn {Scheme Procedure} port-mode port
  1040. @deffnx {C Function} scm_port_mode (port)
  1041. Return the port modes associated with the open port @var{port}.
  1042. These will not necessarily be identical to the modes used when
  1043. the port was opened, since modes such as "append" which are
  1044. used only during port creation are not retained.
  1045. @end deffn
  1046. @deffn {Scheme Procedure} port-filename port
  1047. @deffnx {C Function} scm_port_filename (port)
  1048. Return the filename associated with @var{port}, or @code{#f} if no
  1049. filename is associated with the port.
  1050. @var{port} must be open; @code{port-filename} cannot be used once the
  1051. port is closed.
  1052. @end deffn
  1053. @deffn {Scheme Procedure} set-port-filename! port filename
  1054. @deffnx {C Function} scm_set_port_filename_x (port, filename)
  1055. Change the filename associated with @var{port}, using the current input
  1056. port if none is specified. Note that this does not change the port's
  1057. source of data, but only the value that is returned by
  1058. @code{port-filename} and reported in diagnostic output.
  1059. @end deffn
  1060. @deffn {Scheme Procedure} file-port? obj
  1061. @deffnx {C Function} scm_file_port_p (obj)
  1062. Determine whether @var{obj} is a port that is related to a file.
  1063. @end deffn
  1064. @node Bytevector Ports
  1065. @subsubsection Bytevector Ports
  1066. @deffn {Scheme Procedure} open-bytevector-input-port bv [transcoder]
  1067. @deffnx {C Function} scm_open_bytevector_input_port (bv, transcoder)
  1068. Return an input port whose contents are drawn from bytevector @var{bv}
  1069. (@pxref{Bytevectors}).
  1070. @c FIXME: Update description when implemented.
  1071. The @var{transcoder} argument is currently not supported.
  1072. @end deffn
  1073. @deffn {Scheme Procedure} open-bytevector-output-port [transcoder]
  1074. @deffnx {C Function} scm_open_bytevector_output_port (transcoder)
  1075. Return two values: a binary output port and a procedure. The latter
  1076. should be called with zero arguments to obtain a bytevector containing
  1077. the data accumulated by the port, as illustrated below.
  1078. @lisp
  1079. (call-with-values
  1080. (lambda ()
  1081. (open-bytevector-output-port))
  1082. (lambda (port get-bytevector)
  1083. (display "hello" port)
  1084. (get-bytevector)))
  1085. @result{} #vu8(104 101 108 108 111)
  1086. @end lisp
  1087. @c FIXME: Update description when implemented.
  1088. The @var{transcoder} argument is currently not supported.
  1089. @end deffn
  1090. @deffn {Scheme Procedure} call-with-output-bytevector proc
  1091. Call the one-argument procedure @var{proc} with a newly created
  1092. bytevector output port. When the function returns, the bytevector
  1093. composed of the characters written into the port is returned.
  1094. @var{proc} should not close the port.
  1095. @end deffn
  1096. @deffn {Scheme Procedure} call-with-input-bytevector bytevector proc
  1097. Call the one-argument procedure @var{proc} with a newly created input
  1098. port from which @var{bytevector}'s contents may be read. The values
  1099. yielded by the @var{proc} is returned.
  1100. @end deffn
  1101. @node String Ports
  1102. @subsubsection String Ports
  1103. @cindex String port
  1104. @cindex Port, string
  1105. @deffn {Scheme Procedure} call-with-output-string proc
  1106. @deffnx {C Function} scm_call_with_output_string (proc)
  1107. Calls the one-argument procedure @var{proc} with a newly created output
  1108. port. When the function returns, the string composed of the characters
  1109. written into the port is returned. @var{proc} should not close the port.
  1110. @end deffn
  1111. @deffn {Scheme Procedure} call-with-input-string string proc
  1112. @deffnx {C Function} scm_call_with_input_string (string, proc)
  1113. Calls the one-argument procedure @var{proc} with a newly
  1114. created input port from which @var{string}'s contents may be
  1115. read. The value yielded by the @var{proc} is returned.
  1116. @end deffn
  1117. @deffn {Scheme Procedure} with-output-to-string thunk
  1118. Calls the zero-argument procedure @var{thunk} with the current output
  1119. port set temporarily to a new string port. It returns a string
  1120. composed of the characters written to the current output.
  1121. @end deffn
  1122. @deffn {Scheme Procedure} with-input-from-string string thunk
  1123. Calls the zero-argument procedure @var{thunk} with the current input
  1124. port set temporarily to a string port opened on the specified
  1125. @var{string}. The value yielded by @var{thunk} is returned.
  1126. @end deffn
  1127. @deffn {Scheme Procedure} open-input-string str
  1128. @deffnx {C Function} scm_open_input_string (str)
  1129. Take a string and return an input port that delivers characters
  1130. from the string. The port can be closed by
  1131. @code{close-input-port}, though its storage will be reclaimed
  1132. by the garbage collector if it becomes inaccessible.
  1133. @end deffn
  1134. @deffn {Scheme Procedure} open-output-string
  1135. @deffnx {C Function} scm_open_output_string ()
  1136. Return an output port that will accumulate characters for
  1137. retrieval by @code{get-output-string}. The port can be closed
  1138. by the procedure @code{close-output-port}, though its storage
  1139. will be reclaimed by the garbage collector if it becomes
  1140. inaccessible.
  1141. @end deffn
  1142. @deffn {Scheme Procedure} get-output-string port
  1143. @deffnx {C Function} scm_get_output_string (port)
  1144. Given an output port created by @code{open-output-string},
  1145. return a string consisting of the characters that have been
  1146. output to the port so far.
  1147. @code{get-output-string} must be used before closing @var{port}, once
  1148. closed the string cannot be obtained.
  1149. @end deffn
  1150. With string ports, the port-encoding is treated differently than other
  1151. types of ports. When string ports are created, they do not inherit a
  1152. character encoding from the current locale. They are given a
  1153. default locale that allows them to handle all valid string characters.
  1154. Typically one should not modify a string port's character encoding
  1155. away from its default. @xref{Encoding}.
  1156. @node Custom Ports
  1157. @subsubsection Custom Ports
  1158. Custom ports allow the user to provide input and handle output via
  1159. user-supplied procedures. Guile currently only provides custom binary
  1160. ports, not textual ports; for custom textual ports, @xref{Soft Ports}.
  1161. We should add the R6RS custom textual port interfaces though.
  1162. Contributions are appreciated.
  1163. @cindex custom binary input ports
  1164. @deffn {Scheme Procedure} make-custom-binary-input-port id read! get-position set-position! close
  1165. Return a new custom binary input port@footnote{This is similar in spirit
  1166. to Guile's @dfn{soft ports} (@pxref{Soft Ports}).} named @var{id} (a
  1167. string) whose input is drained by invoking @var{read!} and passing it a
  1168. bytevector, an index where bytes should be written, and the number of
  1169. bytes to read. The @code{read!} procedure must return an integer
  1170. indicating the number of bytes read, or @code{0} to indicate the
  1171. end-of-file.
  1172. Optionally, if @var{get-position} is not @code{#f}, it must be a thunk
  1173. that will be called when @code{port-position} is invoked on the custom
  1174. binary port and should return an integer indicating the position within
  1175. the underlying data stream; if @var{get-position} was not supplied, the
  1176. returned port does not support @code{port-position}.
  1177. Likewise, if @var{set-position!} is not @code{#f}, it should be a
  1178. one-argument procedure. When @code{set-port-position!} is invoked on the
  1179. custom binary input port, @var{set-position!} is passed an integer
  1180. indicating the position of the next byte is to read.
  1181. Finally, if @var{close} is not @code{#f}, it must be a thunk. It is
  1182. invoked when the custom binary input port is closed.
  1183. The returned port is fully buffered by default, but its buffering mode
  1184. can be changed using @code{setvbuf} (@pxref{Buffering}).
  1185. Using a custom binary input port, the @code{open-bytevector-input-port}
  1186. procedure (@pxref{Bytevector Ports}) could be implemented as follows:
  1187. @lisp
  1188. (define (open-bytevector-input-port source)
  1189. (define position 0)
  1190. (define length (bytevector-length source))
  1191. (define (read! bv start count)
  1192. (let ((count (min count (- length position))))
  1193. (bytevector-copy! source position
  1194. bv start count)
  1195. (set! position (+ position count))
  1196. count))
  1197. (define (get-position) position)
  1198. (define (set-position! new-position)
  1199. (set! position new-position))
  1200. (make-custom-binary-input-port "the port" read!
  1201. get-position set-position!
  1202. #f))
  1203. (read (open-bytevector-input-port (string->utf8 "hello")))
  1204. @result{} hello
  1205. @end lisp
  1206. @end deffn
  1207. @cindex custom binary output ports
  1208. @deffn {Scheme Procedure} make-custom-binary-output-port id write! get-position set-position! close
  1209. Return a new custom binary output port named @var{id} (a string) whose
  1210. output is sunk by invoking @var{write!} and passing it a bytevector, an
  1211. index where bytes should be read from this bytevector, and the number of
  1212. bytes to be ``written''. The @code{write!} procedure must return an
  1213. integer indicating the number of bytes actually written; when it is
  1214. passed @code{0} as the number of bytes to write, it should behave as
  1215. though an end-of-file was sent to the byte sink.
  1216. The other arguments are as for @code{make-custom-binary-input-port}.
  1217. @end deffn
  1218. @cindex custom binary input/output ports
  1219. @deffn {Scheme Procedure} make-custom-binary-input/output-port id read! write! get-position set-position! close
  1220. Return a new custom binary input/output port named @var{id} (a string).
  1221. The various arguments are the same as for The other arguments are as for
  1222. @code{make-custom-binary-input-port} and
  1223. @code{make-custom-binary-output-port}. If buffering is enabled on the
  1224. port, as is the case by default, input will be buffered in both
  1225. directions; @xref{Buffering}. If the @var{set-position!} function is
  1226. provided and not @code{#f}, then the port will also be marked as
  1227. random-access, causing the buffer to be flushed between reads and
  1228. writes.
  1229. @end deffn
  1230. @node Soft Ports
  1231. @subsubsection Soft Ports
  1232. @cindex Soft port
  1233. @cindex Port, soft
  1234. A @dfn{soft port} is a port based on a vector of procedures capable of
  1235. accepting or delivering characters. It allows emulation of I/O ports.
  1236. @deffn {Scheme Procedure} make-soft-port pv modes
  1237. Return a port capable of receiving or delivering characters as
  1238. specified by the @var{modes} string (@pxref{File Ports,
  1239. open-file}). @var{pv} must be a vector of length 5 or 6. Its
  1240. components are as follows:
  1241. @enumerate 0
  1242. @item
  1243. procedure accepting one character for output
  1244. @item
  1245. procedure accepting a string for output
  1246. @item
  1247. thunk for flushing output
  1248. @item
  1249. thunk for getting one character
  1250. @item
  1251. thunk for closing port (not by garbage collection)
  1252. @item
  1253. (if present and not @code{#f}) thunk for computing the number of
  1254. characters that can be read from the port without blocking.
  1255. @end enumerate
  1256. For an output-only port only elements 0, 1, 2, and 4 need be
  1257. procedures. For an input-only port only elements 3 and 4 need
  1258. be procedures. Thunks 2 and 4 can instead be @code{#f} if
  1259. there is no useful operation for them to perform.
  1260. If thunk 3 returns @code{#f} or an @code{eof-object}
  1261. (@pxref{Input, eof-object?, ,r5rs, The Revised^5 Report on
  1262. Scheme}) it indicates that the port has reached end-of-file.
  1263. For example:
  1264. @lisp
  1265. (define stdout (current-output-port))
  1266. (define p (make-soft-port
  1267. (vector
  1268. (lambda (c) (write c stdout))
  1269. (lambda (s) (display s stdout))
  1270. (lambda () (display "." stdout))
  1271. (lambda () (char-upcase (read-char)))
  1272. (lambda () (display "@@" stdout)))
  1273. "rw"))
  1274. (write p p) @result{} #<input-output: soft 8081e20>
  1275. @end lisp
  1276. @end deffn
  1277. @node Void Ports
  1278. @subsubsection Void Ports
  1279. @cindex Void port
  1280. @cindex Port, void
  1281. This kind of port causes any data to be discarded when written to, and
  1282. always returns the end-of-file object when read from.
  1283. @deffn {Scheme Procedure} %make-void-port mode
  1284. @deffnx {C Function} scm_sys_make_void_port (mode)
  1285. Create and return a new void port. A void port acts like
  1286. @file{/dev/null}. The @var{mode} argument
  1287. specifies the input/output modes for this port: see the
  1288. documentation for @code{open-file} in @ref{File Ports}.
  1289. @end deffn
  1290. @node Venerable Port Interfaces
  1291. @subsection Venerable Port Interfaces
  1292. Over the 25 years or so that Guile has been around, its port system has
  1293. evolved, adding many useful features. At the same time there have been
  1294. four major Scheme standards released in those 25 years, which also
  1295. evolve the common Scheme understanding of what a port interface should
  1296. be. Alas, it would be too much to ask for all of these evolutionary
  1297. branches to be consistent. Some of Guile's original interfaces don't
  1298. mesh with the later Scheme standards, and yet Guile can't just drop old
  1299. interfaces. Sadly as well, the R6RS and R7RS standards both part from a
  1300. base of R5RS, but end up in different and somewhat incompatible designs.
  1301. Guile's approach is to pick a set of port primitives that make sense
  1302. together. We document that set of primitives, design our internal
  1303. interfaces around them, and recommend them to users. As the R6RS I/O
  1304. system is the most capable standard that Scheme has yet produced in this
  1305. domain, we mostly recommend that; @code{(ice-9 binary-ports)} and
  1306. @code{(ice-9 textual-ports)} are wholly modelled on @code{(rnrs io
  1307. ports)}. Guile does not wholly copy R6RS, however; @xref{R6RS
  1308. Incompatibilities}.
  1309. At the same time, we have many venerable port interfaces, lore handed
  1310. down to us from our hacker ancestors. Most of these interfaces even
  1311. predate the expectation that Scheme should have modules, so they are
  1312. present in the default environment. In Guile we support them as well
  1313. and we have no plans to remove them, but again we don't recommend them
  1314. for new users.
  1315. @rnindex char-ready?
  1316. @deffn {Scheme Procedure} char-ready? [port]
  1317. Return @code{#t} if a character is ready on input @var{port}
  1318. and return @code{#f} otherwise. If @code{char-ready?} returns
  1319. @code{#t} then the next @code{read-char} operation on
  1320. @var{port} is guaranteed not to hang. If @var{port} is a file
  1321. port at end of file then @code{char-ready?} returns @code{#t}.
  1322. @code{char-ready?} exists to make it possible for a
  1323. program to accept characters from interactive ports without
  1324. getting stuck waiting for input. Any input editors associated
  1325. with such ports must make sure that characters whose existence
  1326. has been asserted by @code{char-ready?} cannot be rubbed out.
  1327. If @code{char-ready?} were to return @code{#f} at end of file,
  1328. a port at end of file would be indistinguishable from an
  1329. interactive port that has no ready characters.
  1330. Note that @code{char-ready?} only works reliably for terminals and
  1331. sockets with one-byte encodings. Under the hood it will return
  1332. @code{#t} if the port has any input buffered, or if the file descriptor
  1333. that backs the port polls as readable, indicating that Guile can fetch
  1334. more bytes from the kernel. However being able to fetch one byte
  1335. doesn't mean that a full character is available; @xref{Encoding}. Also,
  1336. on many systems it's possible for a file descriptor to poll as readable,
  1337. but then block when it comes time to read bytes. Note also that on
  1338. Linux kernels, all file ports backed by files always poll as readable.
  1339. For non-file ports, this procedure always returns @code{#t}, except for
  1340. soft ports, which have a @code{char-ready?} handler. @xref{Soft Ports}.
  1341. In short, this is a legacy procedure whose semantics are hard to
  1342. provide. However it is a useful check to see if any input is buffered.
  1343. @xref{Non-Blocking I/O}.
  1344. @end deffn
  1345. @rnindex read-char
  1346. @deffn {Scheme Procedure} read-char [port]
  1347. The same as @code{get-char}, except that @var{port} defaults to the
  1348. current input port. @xref{Textual I/O}.
  1349. @end deffn
  1350. @rnindex peek-char
  1351. @deffn {Scheme Procedure} peek-char [port]
  1352. The same as @code{lookahead-char}, except that @var{port} defaults to
  1353. the current input port. @xref{Textual I/O}.
  1354. @end deffn
  1355. @deffn {Scheme Procedure} unread-char cobj [port]
  1356. The same as @code{unget-char}, except that @var{port} defaults to the
  1357. current input port, and the arguments are swapped. @xref{Textual I/O}.
  1358. @end deffn
  1359. @deffn {Scheme Procedure} unread-string str port
  1360. @deffnx {C Function} scm_unread_string (str, port)
  1361. The same as @code{unget-string}, except that @var{port} defaults to the
  1362. current input port, and the arguments are swapped. @xref{Textual I/O}.
  1363. @end deffn
  1364. @rnindex newline
  1365. @deffn {Scheme Procedure} newline [port]
  1366. Send a newline to @var{port}. If @var{port} is omitted, send to the
  1367. current output port. Equivalent to @code{(put-char port #\newline)}.
  1368. @end deffn
  1369. @rnindex write-char
  1370. @deffn {Scheme Procedure} write-char chr [port]
  1371. The same as @code{put-char}, except that @var{port} defaults to the
  1372. current input port, and the arguments are swapped. @xref{Textual I/O}.
  1373. @end deffn
  1374. @node Using Ports from C
  1375. @subsection Using Ports from C
  1376. Guile's C interfaces provides some niceties for sending and receiving
  1377. bytes and characters in a way that works better with C.
  1378. @deftypefn {C Function} size_t scm_c_read (SCM port, void *buffer, size_t size)
  1379. Read up to @var{size} bytes from @var{port} and store them in
  1380. @var{buffer}. The return value is the number of bytes actually read,
  1381. which can be less than @var{size} if end-of-file has been reached.
  1382. Note that as this is a binary input procedure, this function does not
  1383. update @code{port-line} and @code{port-column} (@pxref{Textual I/O}).
  1384. @end deftypefn
  1385. @deftypefn {C Function} void scm_c_write (SCM port, const void *buffer, size_t size)
  1386. Write @var{size} bytes at @var{buffer} to @var{port}.
  1387. Note that as this is a binary output procedure, this function does not
  1388. update @code{port-line} and @code{port-column} (@pxref{Textual I/O}).
  1389. @end deftypefn
  1390. @deftypefn {C Function} size_t scm_c_read_bytes (SCM port, SCM bv, size_t start, size_t count)
  1391. @deftypefnx {C Function} void scm_c_write_bytes (SCM port, SCM bv, size_t start, size_t count)
  1392. Like @code{scm_c_read} and @code{scm_c_write}, but reading into or
  1393. writing from the bytevector @var{bv}. @var{count} indicates the byte
  1394. index at which to start in the bytevector, and the read or write will
  1395. continue for @var{count} bytes.
  1396. @end deftypefn
  1397. @deftypefn {C Function} void scm_unget_bytes (const unsigned char *buf, size_t len, SCM port)
  1398. @deftypefnx {C Function} void scm_unget_byte (int c, SCM port)
  1399. @deftypefnx {C Function} void scm_ungetc (scm_t_wchar c, SCM port)
  1400. Like @code{unget-bytevector}, @code{unget-byte}, and @code{unget-char},
  1401. respectively. @xref{Textual I/O}.
  1402. @end deftypefn
  1403. @deftypefn {C Function} void scm_c_put_latin1_chars (SCM port, const scm_t_uint8 *buf, size_t len)
  1404. @deftypefnx {C Function} void scm_c_put_utf32_chars (SCM port, const scm_t_uint32 *buf, size_t len);
  1405. Write a string to @var{port}. In the first case, the
  1406. @code{scm_t_uint8*} buffer is a string in the latin-1 encoding. In the
  1407. second, the @code{scm_t_uint32*} buffer is a string in the UTF-32
  1408. encoding. These routines will update the port's line and column.
  1409. @end deftypefn
  1410. @node I/O Extensions
  1411. @subsection Implementing New Port Types in C
  1412. This section describes how to implement a new port type in C. Although
  1413. ports support many operations, as a data structure they present an
  1414. opaque interface to the user. To the port implementor, you have two
  1415. pieces of information to work with: the port type, and the port's
  1416. ``stream''. The port type is an opaque pointer allocated when defining
  1417. your port type. It is your key into the port API, and it helps you
  1418. identify which ports are actually yours. The ``stream'' is a pointer
  1419. you control, and which you set when you create a port. Get a stream
  1420. from a port using the @code{SCM_STREAM} macro. Note that your port
  1421. methods are only ever called with ports of your type.
  1422. A port type is created by calling @code{scm_make_port_type}. Once you
  1423. have your port type, you can create ports with @code{scm_c_make_port},
  1424. or @code{scm_c_make_port_with_encoding}.
  1425. @deftypefun scm_t_port_type* scm_make_port_type (char *name, size_t (*read) (SCM port, SCM dst, size_t start, size_t count), size_t (*write) (SCM port, SCM src, size_t start, size_t count))
  1426. Define a new port type. The @var{name}, @var{read} and @var{write}
  1427. parameters are initial values for those port type fields, as described
  1428. below. The other fields are initialized with default values and can be
  1429. changed later.
  1430. @end deftypefun
  1431. @deftypefun SCM scm_c_make_port_with_encoding (scm_t_port_type *type, unsigned long mode_bits, SCM encoding, SCM conversion_strategy, scm_t_bits stream)
  1432. @deftypefunx SCM scm_c_make_port (scm_t_port_type *type, unsigned long mode_bits, scm_t_bits stream)
  1433. Make a port with the given @var{type}. The @var{stream} indicates the
  1434. private data associated with the port, which your port implementation
  1435. may later retrieve with @code{SCM_STREAM}. The mode bits should include
  1436. one or more of the flags @code{SCM_RDNG} or @code{SCM_WRTNG}, indicating
  1437. that the port is an input and/or an output port, respectively. The mode
  1438. bits may also include @code{SCM_BUF0} or @code{SCM_BUFLINE}, indicating
  1439. that the port should be unbuffered or line-buffered, respectively. The
  1440. default is that the port will be block-buffered. @xref{Buffering}.
  1441. As you would imagine, @var{encoding} and @var{conversion_strategy}
  1442. specify the port's initial textual encoding and conversion strategy.
  1443. Both are symbols. @code{scm_c_make_port} is the same as
  1444. @code{scm_c_make_port_with_encoding}, except it uses the default port
  1445. encoding and conversion strategy.
  1446. @end deftypefun
  1447. The port type has a number of associate procedures and properties which
  1448. collectively implement the port's behavior. Creating a new port type
  1449. mostly involves writing these procedures.
  1450. @table @code
  1451. @item name
  1452. A pointer to a NUL terminated string: the name of the port type. This
  1453. property is initialized via the first argument to
  1454. @code{scm_make_port_type}.
  1455. @item read
  1456. A port's @code{read} implementation fills read buffers. It should copy
  1457. bytes to the supplied bytevector @code{dst}, starting at offset
  1458. @code{start} and continuing for @code{count} bytes, returning the number
  1459. of bytes read.
  1460. @item write
  1461. A port's @code{write} implementation flushes write buffers to the
  1462. mutable store.
  1463. It should write out bytes from the supplied bytevector @code{src},
  1464. starting at offset @code{start} and continuing for @code{count} bytes,
  1465. and return the number of bytes that were written.
  1466. @item read_wait_fd
  1467. @itemx write_wait_fd
  1468. If a port's @code{read} or @code{write} function returns @code{(size_t)
  1469. -1}, that indicates that reading or writing would block. In that case
  1470. to preserve the illusion of a blocking read or write operation, Guile's
  1471. C port run-time will @code{poll} on the file descriptor returned by
  1472. either the port's @code{read_wait_fd} or @code{write_wait_fd} function.
  1473. Set using
  1474. @deftypefun void scm_set_port_read_wait_fd (scm_t_port_type *type, int (*wait_fd) (SCM port))
  1475. @deftypefunx void scm_set_port_write_wait_fd (scm_t_port_type *type, int (*wait_fd) (SCM port))
  1476. @end deftypefun
  1477. Only a port type which implements the @code{read_wait_fd} or
  1478. @code{write_wait_fd} port methods can usefully return @code{(size_t) -1}
  1479. from a read or write function. @xref{Non-Blocking I/O}, for more on
  1480. non-blocking I/O in Guile.
  1481. @item print
  1482. Called when @code{write} is called on the port, to print a port
  1483. description. For example, for a file port it may produce something
  1484. like: @code{#<input: /etc/passwd 3>}. Set using
  1485. @deftypefun void scm_set_port_print (scm_t_port_type *type, int (*print) (SCM port, SCM dest_port, scm_print_state *pstate))
  1486. The first argument @var{port} is the port being printed, the second
  1487. argument @var{dest_port} is where its description should go.
  1488. @end deftypefun
  1489. @item close
  1490. Called when the port is closed. It should free any resources used by
  1491. the port. Set using
  1492. @deftypefun void scm_set_port_close (scm_t_port_type *type, void (*close) (SCM port))
  1493. @end deftypefun
  1494. By default, ports that are garbage collected just go away without
  1495. closing. If your port type needs to release some external resource like
  1496. a file descriptor, or needs to make sure that its internal buffers are
  1497. flushed even if the port is collected while it was open, then mark the
  1498. port type as needing a close on GC.
  1499. @deftypefun void scm_set_port_needs_close_on_gc (scm_t_port_type *type, int needs_close_p)
  1500. @end deftypefun
  1501. @item seek
  1502. Set the current position of the port. Guile will flush read and/or
  1503. write buffers before seeking, as appropriate.
  1504. @deftypefun void scm_set_port_seek (scm_t_port_type *type, scm_t_off (*seek) (SCM port, scm_t_off offset, int whence))
  1505. @end deftypefun
  1506. @item truncate
  1507. Truncate the port data to be specified length. Guile will flush buffers
  1508. before hand, as appropriate. Set using
  1509. @deftypefun void scm_set_port_truncate (scm_t_port_type *type, void (*truncate) (SCM port, scm_t_off length))
  1510. @end deftypefun
  1511. @item random_access_p
  1512. Determine whether this port is a random-access port.
  1513. @cindex random access
  1514. Seeking on a random-access port with buffered input, or switching to
  1515. writing after reading, will cause the buffered input to be discarded and
  1516. Guile will seek the port back the buffered number of bytes. Likewise
  1517. seeking on a random-access port with buffered output, or switching to
  1518. reading after writing, will flush pending bytes with a call to the
  1519. @code{write} procedure. @xref{Buffering}.
  1520. Indicate to Guile that your port needs this behavior by returning a
  1521. nonzero value from your @code{random_access_p} function. The default
  1522. implementation of this function returns nonzero if the port type
  1523. supplies a seek implementation.
  1524. @deftypefun void scm_set_port_random_access_p (scm_t_port_type *type, int (*random_access_p) (SCM port));
  1525. @end deftypefun
  1526. @item get_natural_buffer_sizes
  1527. Guile will internally attach buffers to ports. An input port always has
  1528. a read buffer and an output port always has a write buffer.
  1529. @xref{Buffering}. A port buffer consists of a bytevector, along with
  1530. some cursors into that bytevector denoting where to get and put data.
  1531. Port implementations generally don't have to be concerned with
  1532. buffering: a port type's @code{read} or @code{write} function will
  1533. receive the buffer's bytevector as an argument, along with an offset and
  1534. a length into that bytevector, and should then either fill or empty that
  1535. bytevector. However in some cases, port implementations may be able to
  1536. provide an appropriate default buffer size to Guile.
  1537. @deftypefun void scm_set_port_get_natural_buffer_sizes @
  1538. (scm_t_port_type *type, void (*get_natural_buffer_sizes) (SCM, size_t *read_buf_size, size_t *write_buf_size))
  1539. Fill in @var{read_buf_size} and @var{write_buf_size} with an appropriate buffer size for this port, if one is known.
  1540. @end deftypefun
  1541. File ports implement a @code{get_natural_buffer_sizes} to let the
  1542. operating system inform Guile about the appropriate buffer sizes for the
  1543. particular file opened by the port.
  1544. @end table
  1545. Note that calls to all of these methods can proceed in parallel and
  1546. concurrently and from any thread up until the point that the port is
  1547. closed. The call to @code{close} will happen when no other method is
  1548. running, and no method will be called after the @code{close} method is
  1549. called. If your port implementation needs mutual exclusion to prevent
  1550. concurrency, it is responsible for locking appropriately.
  1551. @node Non-Blocking I/O
  1552. @subsection Non-Blocking I/O
  1553. Most ports in Guile are @dfn{blocking}: when you try to read a character
  1554. from a port, Guile will block on the read until a character is ready, or
  1555. end-of-stream is detected. Likewise whenever Guile goes to write
  1556. (possibly buffered) data to an output port, Guile will block until all
  1557. the data is written.
  1558. Interacting with ports in blocking mode is very convenient: you can
  1559. write straightforward, sequential algorithms whose code flow reflects
  1560. the flow of data. However, blocking I/O has two main limitations.
  1561. The first is that it's easy to get into a situation where code is
  1562. waiting on data. Time spent waiting on data when code could be doing
  1563. something else is wasteful and prevents your program from reaching its
  1564. peak throughput. If you implement a web server that sequentially
  1565. handles requests from clients, it's very easy for the server to end up
  1566. waiting on a client to finish its HTTP request, or waiting on it to
  1567. consume the response. The end result is that you are able to serve
  1568. fewer requests per second than you'd like to serve.
  1569. The second limitation is related: a blocking parser over user-controlled
  1570. input is a denial-of-service vulnerability. Indeed the so-called ``slow
  1571. loris'' attack of the early 2010s was just that: an attack on common web
  1572. servers that drip-fed HTTP requests, one character at a time. All it
  1573. took was a handful of slow loris connections to occupy an entire web
  1574. server.
  1575. In Guile we would like to preserve the ability to write straightforward
  1576. blocking networking processes of all kinds, but under the hood to allow
  1577. those processes to suspend their requests if they would block.
  1578. To do this, the first piece is to allow Guile ports to declare
  1579. themselves as being nonblocking. This is currently supported only for
  1580. file ports, which also includes sockets, terminals, or any other port
  1581. that is backed by a file descriptor. To do that, we use an arcane UNIX
  1582. incantation:
  1583. @example
  1584. (let ((flags (fcntl socket F_GETFL)))
  1585. (fcntl socket F_SETFL (logior O_NONBLOCK flags)))
  1586. @end example
  1587. Now the file descriptor is open in non-blocking mode. If Guile tries to
  1588. read or write from this file and the read or write returns a result
  1589. indicating that more data can only be had by doing a blocking read or
  1590. write, Guile will block by polling on the socket's @code{read-wait-fd}
  1591. or @code{write-wait-fd}, to preserve the illusion of a blocking read or
  1592. write. @xref{I/O Extensions} for more on those internal interfaces.
  1593. So far we have just reproduced the status quo: the file descriptor is
  1594. non-blocking, but the operations on the port do block. To go farther,
  1595. it would be nice if we could suspend the ``thread'' using delimited
  1596. continuations, and only resume the thread once the file descriptor is
  1597. readable or writable. (@xref{Prompts}).
  1598. But here we run into a difficulty. The ports code is implemented in C,
  1599. which means that although we can suspend the computation to some outer
  1600. prompt, we can't resume it because Guile can't resume delimited
  1601. continuations that capture the C stack.
  1602. To overcome this difficulty we have created a compatible but entirely
  1603. parallel implementation of port operations. To use this implementation,
  1604. do the following:
  1605. @example
  1606. (use-modules (ice-9 suspendable-ports))
  1607. (install-suspendable-ports!)
  1608. @end example
  1609. This will replace the core I/O primitives like @code{get-char} and
  1610. @code{put-bytevector} with new versions that are exactly the same as the
  1611. ones in the standard library, but with two differences. One is that
  1612. when a read or a write would block, the suspendable port operations call
  1613. out the value of the @code{current-read-waiter} or
  1614. @code{current-write-waiter} parameter, as appropriate.
  1615. @xref{Parameters}. The default read and write waiters do the same thing
  1616. that the C read and write waiters do, which is to poll. User code can
  1617. parameterize the waiters, though, enabling the computation to suspend
  1618. and allow the program to process other I/O operations. Because the new
  1619. suspendable ports implementation is written in Scheme, that suspended
  1620. computation can resume again later when it is able to make progress.
  1621. Success!
  1622. The other main difference is that because the new ports implementation
  1623. is written in Scheme, it is slower than C, currently by a factor of 3 or
  1624. 4, though it depends on many factors. For this reason we have to keep
  1625. the C implementations as the default ones. One day when Guile's
  1626. compiler is better, we can close this gap and have only one port
  1627. operation implementation again.
  1628. Note that Guile does not currently include an implementation of the
  1629. facility to suspend the current thread and schedule other threads in the
  1630. meantime. Before adding such a thing, we want to make sure that we're
  1631. providing the right primitives that can be used to build schedulers and
  1632. other user-space concurrency patterns, and that the patterns that we
  1633. settle on are the right patterns. In the meantime, have a look at 8sync
  1634. (@url{https://gnu.org/software/8sync}) for a prototype of an
  1635. asynchronous I/O and concurrency facility.
  1636. @deffn {Scheme Procedure} install-suspendable-ports!
  1637. Replace the core ports implementation with suspendable ports, as
  1638. described above. This will mutate the values of the bindings like
  1639. @code{get-char}, @code{put-u8}, and so on in place.
  1640. @end deffn
  1641. @deffn {Scheme Procedure} uninstall-suspendable-ports!
  1642. Restore the original core ports implementation, un-doing the effect of
  1643. @code{install-suspendable-ports!}.
  1644. @end deffn
  1645. @deffn {Scheme Parameter} current-read-waiter
  1646. @deffnx {Scheme Parameter} current-write-waiter
  1647. Parameters whose values are procedures of one argument, called when a
  1648. suspendable port operation would block on a port while reading or
  1649. writing, respectively. The default values of these parameters do a
  1650. blocking @code{poll} on the port's file descriptor. The procedures are
  1651. passed the port in question as their one argument.
  1652. @end deffn
  1653. @node BOM Handling
  1654. @subsection Handling of Unicode Byte Order Marks
  1655. @cindex BOM
  1656. @cindex byte order mark
  1657. This section documents the finer points of Guile's handling of Unicode
  1658. byte order marks (BOMs). A byte order mark (U+FEFF) is typically found
  1659. at the start of a UTF-16 or UTF-32 stream, to allow readers to reliably
  1660. determine the byte order. Occasionally, a BOM is found at the start of
  1661. a UTF-8 stream, but this is much less common and not generally
  1662. recommended.
  1663. Guile attempts to handle BOMs automatically, and in accordance with the
  1664. recommendations of the Unicode Standard, when the port encoding is set
  1665. to @code{UTF-8}, @code{UTF-16}, or @code{UTF-32}. In brief, Guile
  1666. automatically writes a BOM at the start of a UTF-16 or UTF-32 stream,
  1667. and automatically consumes one from the start of a UTF-8, UTF-16, or
  1668. UTF-32 stream.
  1669. As specified in the Unicode Standard, a BOM is only handled specially at
  1670. the start of a stream, and only if the port encoding is set to
  1671. @code{UTF-8}, @code{UTF-16} or @code{UTF-32}. If the port encoding is
  1672. set to @code{UTF-16BE}, @code{UTF-16LE}, @code{UTF-32BE}, or
  1673. @code{UTF-32LE}, then BOMs are @emph{not} handled specially, and none of
  1674. the special handling described in this section applies.
  1675. @itemize @bullet
  1676. @item
  1677. To ensure that Guile will properly detect the byte order of a UTF-16 or
  1678. UTF-32 stream, you must perform a textual read before any writes, seeks,
  1679. or binary I/O. Guile will not attempt to read a BOM unless a read is
  1680. explicitly requested at the start of the stream.
  1681. @item
  1682. If a textual write is performed before the first read, then an arbitrary
  1683. byte order will be chosen. Currently, big endian is the default on all
  1684. platforms, but that may change in the future. If you wish to explicitly
  1685. control the byte order of an output stream, set the port encoding to
  1686. @code{UTF-16BE}, @code{UTF-16LE}, @code{UTF-32BE}, or @code{UTF-32LE},
  1687. and explicitly write a BOM (@code{#\xFEFF}) if desired.
  1688. @item
  1689. If @code{set-port-encoding!} is called in the middle of a stream, Guile
  1690. treats this as a new logical ``start of stream'' for purposes of BOM
  1691. handling, and will forget about any BOMs that had previously been seen.
  1692. Therefore, it may choose a different byte order than had been used
  1693. previously. This is intended to support multiple logical text streams
  1694. embedded within a larger binary stream.
  1695. @item
  1696. Binary I/O operations are not guaranteed to update Guile's notion of
  1697. whether the port is at the ``start of the stream'', nor are they
  1698. guaranteed to produce or consume BOMs.
  1699. @item
  1700. For ports that support seeking (e.g. normal files), the input and output
  1701. streams are considered linked: if the user reads first, then a BOM will
  1702. be consumed (if appropriate), but later writes will @emph{not} produce a
  1703. BOM. Similarly, if the user writes first, then later reads will
  1704. @emph{not} consume a BOM.
  1705. @item
  1706. For ports that are not random access (e.g. pipes, sockets, and
  1707. terminals), the input and output streams are considered
  1708. @emph{independent} for purposes of BOM handling: the first read will
  1709. consume a BOM (if appropriate), and the first write will @emph{also}
  1710. produce a BOM (if appropriate). However, the input and output streams
  1711. will always use the same byte order.
  1712. @item
  1713. Seeks to the beginning of a file will set the ``start of stream'' flags.
  1714. Therefore, a subsequent textual read or write will consume or produce a
  1715. BOM. However, unlike @code{set-port-encoding!}, if a byte order had
  1716. already been chosen for the port, it will remain in effect after a seek,
  1717. and cannot be changed by the presence of a BOM. Seeks anywhere other
  1718. than the beginning of a file clear the ``start of stream'' flags.
  1719. @end itemize
  1720. @c Local Variables:
  1721. @c TeX-master: "guile.texi"
  1722. @c End: