1chan(n)                      Tcl Built-In Commands                     chan(n)
2
3
4
5______________________________________________________________________________
6

NAME

8       chan - Read, write and manipulate channels
9

SYNOPSIS

11       chan option ?arg arg ...?
12_________________________________________________________________
13

DESCRIPTION

15       This  command  provides several operations for reading from, writing to
16       and otherwise manipulating open channels (such  as  have  been  created
17       with the open and socket commands, or the default named channels stdin,
18       stdout or stderr which correspond to the process's standard input, out‐
19       put  and error streams respectively).  Option indicates what to do with
20       the channel; any unique abbreviation for option  is  acceptable.  Valid
21       options are:
22
23       chan blocked channelId
24              This  tests  whether  the  last  input  operation on the channel
25              called channelId failed because it would have  otherwise  caused
26              the  process  to  block,  and returns 1 if that was the case. It
27              returns 0 otherwise. Note that this only ever returns 1 when the
28              channel has been configured to be non-blocking; all Tcl channels
29              have blocking turned on by default.
30
31       chan close channelId
32              Close and destroy the channel called channelId. Note  that  this
33              deletes all existing file-events registered on the channel.
34
35              As  part  of closing the channel, all buffered output is flushed
36              to the channel's output device, any buffered input is discarded,
37              the underlying operating system resource is closed and channelId
38              becomes unavailable for future use.
39
40              If the channel is blocking, the command does  not  return  until
41              all  output is flushed.  If the channel is nonblocking and there
42              is unflushed output, the channel remains open  and  the  command
43              returns  immediately;  output  will be flushed in the background
44              and the channel will be closed when all  the  flushing  is  com‐
45              plete.
46
47              If  channelId  is a blocking channel for a command pipeline then
48              chan close waits for the child processes to complete.
49
50              If the channel is shared between interpreters, then  chan  close
51              makes  channelId unavailable in the invoking interpreter but has
52              no other effect until  all  of  the  sharing  interpreters  have
53              closed the channel. When the last interpreter in which the chan‐
54              nel is registered invokes chan close  (or  close),  the  cleanup
55              actions  described  above  occur.  See  the interp command for a
56              description of channel sharing.
57
58              Channels  are  automatically  closed  when  an  interpreter   is
59              destroyed  and when the process exits.  Channels are switched to
60              blocking mode, to ensure that all output  is  correctly  flushed
61              before the process exits.
62
63              The  command  returns an empty string, and may generate an error
64              if an error occurs while flushing output.  If  a  command  in  a
65              command  pipeline created with open returns an error, chan close
66              generates an error (similar to the exec command.)
67
68       chan configure channelId ?optionName? ?value? ?optionName value?...
69              Query or set the configuration  options  of  the  channel  named
70              channelId.
71
72              If  no  optionName  or value arguments are supplied, the command
73              returns a list containing alternating option  names  and  values
74              for  the  channel.   If optionName is supplied but no value then
75              the command returns the current value of the given  option.   If
76              one or more pairs of optionName and value are supplied, the com‐
77              mand sets each of the named options to the corresponding  value;
78              in this case the return value is an empty string.
79
80              The  options  described below are supported for all channels. In
81              addition, each channel type may add options that  only  it  sup‐
82              ports.  See  the  manual entry for the command that creates each
83              type of channels for the options  that  that  specific  type  of
84              channel  supports.  For  example,  see  the manual entry for the
85              socket command for its additional options.
86
87              -blocking boolean
88                     The -blocking option determines whether I/O operations on
89                     the  channel can cause the process to block indefinitely.
90                     The value of the option must be a proper  boolean  value.
91                     Channels  are  normally in blocking mode; if a channel is
92                     placed into nonblocking mode it will affect the operation
93                     of  the  chan gets, chan read, chan puts, chan flush, and
94                     chan close commands; see the documentation for those com‐
95                     mands  for  details.   For  nonblocking mode to work cor‐
96                     rectly, the application must be using the Tcl event  loop
97                     (e.g.  by  calling  Tcl_DoOneEvent  or invoking the vwait
98                     command).
99
100              -buffering newValue
101                     If newValue is full then the I/O system will buffer  out‐
102                     put  until  its internal buffer is full or until the chan
103                     flush command is invoked. If newValue is line,  then  the
104                     I/O  system will automatically flush output for the chan‐
105                     nel whenever a newline character is output.  If  newValue
106                     is  none,  the  I/O system will flush automatically after
107                     every output operation.  The default is for -buffering to
108                     be set to full except for channels that connect to termi‐
109                     nal-like devices; for these channels the initial  setting
110                     is  line.   Additionally,  stdin and stdout are initially
111                     set to line, and stderr is set to none.
112
113              -buffersize newSize
114                     Newvalue must be an integer; its value is used to set the
115                     size  of  buffers,  in  bytes, subsequently allocated for
116                     this channel to store input or output. Newvalue must be a
117                     number  of  no more than one million, allowing buffers of
118                     up to one million bytes in size.
119
120              -encoding name
121                     This option is used to specify the encoding of the  chan‐
122                     nel  as  one  of the named encodings returned by encoding
123                     names or the special value binary, so that the  data  can
124                     be  converted  to  and  from Unicode for use in Tcl.  For
125                     instance, in order for Tcl to read characters from a  Ja‐
126                     panese  file in shiftjis and properly process and display
127                     the contents, the encoding  would  be  set  to  shiftjis.
128                     Thereafter,  when  reading from the channel, the bytes in
129                     the Japanese file would be converted to Unicode  as  they
130                     are read.  Writing is also supported - as Tcl strings are
131                     written to the channel they will  automatically  be  con‐
132                     verted to the specified encoding on output.
133
134                     If a file contains pure binary data (for instance, a JPEG
135                     image), the encoding for the channel should be configured
136                     to  be binary.  Tcl will then assign no interpretation to
137                     the data in the file and simply read or write raw  bytes.
138                     The  Tcl  binary  command  can be used to manipulate this
139                     byte-oriented data.  It is  usually  better  to  set  the
140                     -translation  option  to binary when you want to transfer
141                     binary data, as this turns off the other automatic inter‐
142                     pretations of the bytes in the stream as well.
143
144                     The  default  encoding  for  newly opened channels is the
145                     same platform- and locale-dependent system encoding  used
146                     for interfacing with the operating system, as returned by
147                     encoding system.
148
149              -eofchar char
150
151              -eofchar {inChar outChar}
152                     This option supports DOS file systems that use  Control-z
153                     (\x1a) as an end of file marker.  If char is not an empty
154                     string, then this character signals end-of-file  when  it
155                     is encountered during input.  For output, the end-of-file
156                     character is output when the channel is closed.  If  char
157                     is the empty string, then there is no special end of file
158                     character marker.  For read-write channels, a two-element
159                     list  specifies the end of file marker for input and out‐
160                     put, respectively.  As a convenience,  when  setting  the
161                     end-of-file  character  for  a read-write channel you can
162                     specify a single value that will apply  to  both  reading
163                     and  writing.  When querying the end-of-file character of
164                     a read-write channel, a two-element list will  always  be
165                     returned.   The  default  value for -eofchar is the empty
166                     string in all cases except for files under  Windows.   In
167                     that  case  the  -eofchar is Control-z (\x1a) for reading
168                     and the empty string for writing.  The  acceptable  range
169                     for  -eofchar  values  is  \x01 - \x7f; attempting to set
170                     -eofchar to a value outside of this range  will  generate
171                     an error.
172
173              -translation mode
174
175              -translation {inMode outMode}
176                     In  Tcl  scripts  the end of a line is always represented
177                     using a  single  newline  character  (\n).   However,  in
178                     actual  files and devices the end of a line may be repre‐
179                     sented differently on different platforms,  or  even  for
180                     different  devices  on  the  same platform.  For example,
181                     under UNIX newlines are used in files, whereas  carriage-
182                     return-linefeed  sequences  are  normally used in network
183                     connections.  On input (i.e., with  chan  gets  and  chan
184                     read)  the  Tcl  I/O  system automatically translates the
185                     external end-of-line representation into newline  charac‐
186                     ters.  Upon output (i.e., with chan puts), the I/O system
187                     translates newlines to the external end-of-line represen‐
188                     tation.   The default translation mode, auto, handles all
189                     the common  cases  automatically,  but  the  -translation
190                     option  provides  explicit  control  over the end of line
191                     translations.
192
193                     The value associated with -translation is a  single  item
194                     for  read-only  and  write-only channels.  The value is a
195                     two-element list for read-write channels; the read trans‐
196                     lation  mode  is  the  first element of the list, and the
197                     write translation mode is the second element.  As a  con‐
198                     venience,  when  setting the translation mode for a read-
199                     write channel you can specify a single  value  that  will
200                     apply  to  both  reading  and writing.  When querying the
201                     translation mode of a read-write channel,  a  two-element
202                     list  will  always be returned.  The following values are
203                     currently supported:
204
205                     auto   As the input translation mode, auto treats any  of
206                            newline  (lf),  carriage  return (cr), or carriage
207                            return followed by a newline (crlf) as the end  of
208                            line  representation.  The end of line representa‐
209                            tion can even change from  line-to-line,  and  all
210                            cases  are translated to a newline.  As the output
211                            translation mode, auto chooses a platform specific
212                            representation;  for  sockets on all platforms Tcl
213                            chooses crlf, for all Unix flavors, it chooses lf,
214                            and  for the various flavors of Windows it chooses
215                            crlf.  The default  setting  for  -translation  is
216                            auto for both input and output.
217
218                     binary No  end-of-line  translations are performed.  This
219                            is nearly identical to lf  mode,  except  that  in
220                            addition  binary  mode  also  sets the end-of-file
221                            character to the empty string (which disables  it)
222                            and  sets  the  encoding to binary (which disables
223                            encoding  filtering).   See  the  description   of
224                            -eofchar and -encoding for more information.
225
226                     cr     The end of a line in the underlying file or device
227                            is represented by a single carriage return charac‐
228                            ter.   As the input translation mode, cr mode con‐
229                            verts carriage returns to newline characters.   As
230                            the  output  translation  mode, cr mode translates
231                            newline characters to carriage returns.
232
233                     crlf   The end of a line in the underlying file or device
234                            is represented by a carriage return character fol‐
235                            lowed by  a  linefeed  character.   As  the  input
236                            translation  mode,  crlf  mode  converts carriage-
237                            return-linefeed sequences to  newline  characters.
238                            As  the  output translation mode, crlf mode trans‐
239                            lates newline characters to  carriage-return-line‐
240                            feed  sequences.   This  mode is typically used on
241                            Windows platforms and for network connections.
242
243                     lf     The end of a line in the underlying file or device
244                            is  represented  by  a  single  newline (linefeed)
245                            character.  In this  mode  no  translations  occur
246                            during either input or output.  This mode is typi‐
247                            cally used on UNIX platforms.
248
249       chan copy inputChan outputChan ?-size size? ?-command callback?
250              Copy data from the  channel  inputChan,  which  must  have  been
251              opened  for  reading, to the channel outputChan, which must have
252              been opened for writing. The chan  copy  command  leverages  the
253              buffering  in  the  Tcl  I/O system to avoid extra copies and to
254              avoid buffering too much data in main memory when copying  large
255              files to slow destinations like network sockets.
256
257              The chan copy command transfers data from inputChan until end of
258              file or size bytes have been transferred. If no  -size  argument
259              is  given,  then  the copy goes until end of file.  All the data
260              read from inputChan is copied to outputChan.  Without the  -com‐
261              mand  option,  chan  copy  blocks until the copy is complete and
262              returns the number of bytes written to outputChan.
263
264              The -command argument makes chan copy work  in  the  background.
265              In  this case it returns immediately and the callback is invoked
266              later when the copy completes.  The callback is called with  one
267              or  two  additional arguments that indicates how many bytes were
268              written to outputChan.  If an error occurred  during  the  back‐
269              ground  copy, the second argument is the error string associated
270              with the error.  With a background copy, it is not necessary  to
271              put  inputChan  or  outputChan  into non-blocking mode; the chan
272              copy command takes care of that automatically.  However,  it  is
273              necessary  to enter the event loop by using the vwait command or
274              by using Tk.
275
276              You are not allowed to do other I/O operations with inputChan or
277              outputChan  during  a background chan copy.  If either inputChan
278              or outputChan get closed while the copy is in progress, the cur‐
279              rent  copy  is stopped and the command callback is not made.  If
280              inputChan is closed, then all data already queued for outputChan
281              is written out.
282
283              Note  that  inputChan  can  become  readable during a background
284              copy.  You should turn off any chan event or fileevent  handlers
285              during a background copy so those handlers do not interfere with
286              the copy.  Any I/O attempted by a chan event or  fileevent  han‐
287              dler will get a “channel busy” error.
288
289              Chan copy translates end-of-line sequences in inputChan and out‐
290              putChan according to the -translation option for these  channels
291              (see chan configure above).  The translations mean that the num‐
292              ber of bytes read from inputChan can be different than the  num‐
293              ber  of  bytes  written to outputChan.  Only the number of bytes
294              written to outputChan is reported, either as the return value of
295              a  synchronous  chan copy or as the argument to the callback for
296              an asynchronous chan copy.
297
298              Chan copy obeys the encodings and character translations config‐
299              ured  for  the channels. This means that the incoming characters
300              are converted internally first UTF-8 and then into the  encoding
301              of the channel chan copy writes to (see chan configure above for
302              details on the -encoding and -translation options).  No  conver‐
303              sion  is  done  if  both channels are set to encoding binary and
304              have matching translations. If only the output channel is set to
305              encoding  binary the system will write the internal UTF-8 repre‐
306              sentation of the incoming characters. If only the input  channel
307              is set to encoding binary the system will assume that the incom‐
308              ing bytes are valid UTF-8 characters and convert them  according
309              to  the  output  encoding. The behaviour of the system for bytes
310              which are not valid UTF-8 characters is undefined in this case.
311
312       chan create mode cmdPrefix
313              This subcommand creates a new script  level  channel  using  the
314              command  prefix  cmdPrefix  as  its handler. Any such channel is
315              called a reflected channel. The specified command  prefix,  cmd‐
316              Prefix,  must  be  a  non-empty list, and should provide the API
317              described in the reflectedchan manual page. The  handle  of  the
318              new  channel  is  returned as the result of the chan create com‐
319              mand, and the channel is open. Use either close or chan close to
320              remove the channel.
321
322              The  argument  mode  specifies  if the new channel is opened for
323              reading, writing, or both. It has to be a list containing any of
324              the  strings “read” or “write”.  The list must have at least one
325              element, as a channel you can neither write  to  nor  read  from
326              makes  no  sense.  The  handler command for the new channel must
327              support the chosen mode, or an error is thrown.
328
329              The command prefix is executed in the global namespace,  at  the
330              top  of  call  stack,  following  the  appending of arguments as
331              described in the reflectedchan manual page.  Command  resolution
332              happens  at  the  time  of  the  call.  Renaming the command, or
333              destroying it means that the next call of a handler  method  may
334              fail,  causing  the channel command invoking the handler to fail
335              as well. Depending on the subcommand being  invoked,  the  error
336              message may not be able to explain the reason for that failure.
337
338              Every  channel  created  with this subcommand knows which inter‐
339              preter it was created in, and only  ever  executes  its  handler
340              command in that interpreter, even if the channel was shared with
341              and/or was moved into a different  interpreter.  Each  reflected
342              channel  also  knows  the thread it was created in, and executes
343              its handler command only in that thread, even if the channel was
344              moved  into  a  different thread. To this end all invocations of
345              the handler are forwarded to the original thread by posting spe‐
346              cial events to it. This means that the original thread (i.e. the
347              thread that executed the  chan  create  command)  must  have  an
348              active  event loop, i.e. it must be able to process such events.
349              Otherwise the thread sending them will block indefinitely. Dead‐
350              lock may occur.
351
352              Note  that this permits the creation of a channel whose two end‐
353              points live in two different threads,  providing  a  stream-ori‐
354              ented  bridge between these threads. In other words, we can pro‐
355              vide a way for  regular  stream  communication  between  threads
356              instead of having to send commands.
357
358              When  a  thread  or interpreter is deleted, all channels created
359              with this subcommand and using this thread/interpreter as  their
360              computing  base  are  deleted  as well, in all interpreters they
361              have been shared with or moved into, and in whatever thread they
362              have  been transfered to. While this pulls the rug out under the
363              other thread(s) and/or interpreter(s), this cannot  be  avoided.
364              Trying to use such a channel will cause the generation of a reg‐
365              ular error about unknown channel handles.
366
367              This subcommand is safe  and  made  accessible  to  safe  inter‐
368              preters.   While  it arranges for the execution of arbitrary Tcl
369              code the system also makes sure that the code is always executed
370              within the safe interpreter.
371
372       chan eof channelId
373              Test  whether  the  last  input  operation on the channel called
374              channelId failed because the end of the data stream was reached,
375              returning 1 if end-of-file was reached, and 0 otherwise.
376
377       chan event channelId event ?script?
378              Arrange  for  the  Tcl  script  script to be installed as a file
379              event handler to be called whenever the channel called channelId
380              enters  the state described by event (which must be either read‐
381              able or writable); only one such handler may  be  installed  per
382              event per channel at a time.  If script is the empty string, the
383              current handler is deleted (this also happens if the channel  is
384              closed  or  the interpreter deleted).  If script is omitted, the
385              currently installed script is returned (or an empty string if no
386              such  handler  is installed).  The callback is only performed if
387              the event loop is being serviced (e.g. via vwait or update).
388
389              A file event handler is  a  binding  between  a  channel  and  a
390              script,  such  that the script is evaluated whenever the channel
391              becomes readable or writable.  File event handlers are most com‐
392              monly  used to allow data to be received from another process on
393              an event-driven basis, so that  the  receiver  can  continue  to
394              interact  with the user or with other channels while waiting for
395              the data to arrive.  If an application invokes chan gets or chan
396              read  on  a  blocking channel when there is no input data avail‐
397              able, the process will block; until the input data  arrives,  it
398              will  not  be able to service other events, so it will appear to
399              the user to “freeze up”.  With chan event, the process can  tell
400              when data is present and only invoke chan gets or chan read when
401              they will not block.
402
403              A channel is considered to be readable if there is  unread  data
404              available  on  the underlying device.  A channel is also consid‐
405              ered to be readable if there is unread data in an input  buffer,
406              except in the special case where the most recent attempt to read
407              from the channel was a chan gets call that could not find a com‐
408              plete  line  in the input buffer.  This feature allows a file to
409              be read a line at a time in nonblocking mode  using  events.   A
410              channel  is  also considered to be readable if an end of file or
411              error condition is present on the underlying file or device.  It
412              is important for script to check for these conditions and handle
413              them appropriately; for example, if there is  no  special  check
414              for  end  of file, an infinite loop may occur where script reads
415              no data, returns, and is immediately invoked again.
416
417              A channel is considered to be writable if at least one  byte  of
418              data  can  be  written  to the underlying file or device without
419              blocking, or if an error condition is present on the  underlying
420              file or device.  Note that client sockets opened in asynchronous
421              mode become writable when they become connected or if  the  con‐
422              nection fails.
423
424              Event-driven  I/O  works best for channels that have been placed
425              into nonblocking mode  with  the  chan  configure  command.   In
426              blocking mode, a chan puts command may block if you give it more
427              data than the underlying file or device can accept, and  a  chan
428              gets or chan read command will block if you attempt to read more
429              data than is ready; no events will be processed while  the  com‐
430              mands block.  In nonblocking mode chan puts, chan read, and chan
431              gets never block.
432
433              The script for a file event is executed at global level (outside
434              the  context  of  any Tcl procedure) in the interpreter in which
435              the chan event command was invoked.  If an  error  occurs  while
436              executing  the  script  then  the command registered with interp
437              bgerror is used to report the  error.   In  addition,  the  file
438              event  handler  is  deleted if it ever returns an error; this is
439              done in order to prevent infinite loops due to buggy handlers.
440
441       chan flush channelId
442              Ensures that all pending output for the channel called channelId
443              is written.
444
445              If  the  channel is in blocking mode the command does not return
446              until all the buffered output has been flushed to  the  channel.
447              If  the  channel  is in nonblocking mode, the command may return
448              before all buffered output has been flushed; the remainder  will
449              be  flushed  in the background as fast as the underlying file or
450              device is able to absorb it.
451
452       chan gets channelId ?varName?
453              Reads the next line from the channel called channelId.  If  var‐
454              Name  is  not  specified,  the result of the command will be the
455              line that has been read (without a trailing  newline  character)
456              or an empty string upon end-of-file or, in non-blocking mode, if
457              the data available is exhausted. If varName  is  specified,  the
458              line  that  has been read will be written to the variable called
459              varName and result will be the number of  characters  that  have
460              been  read  or -1 if end-of-file was reached or, in non-blocking
461              mode, if the data available is exhausted.
462
463              If an end-of-file occurs while part way through reading a  line,
464              the  partial  line  will  be returned (or written into varName).
465              When varName is not specified, the end-of-file case can be  dis‐
466              tinguished  from  an  empty line using the chan eof command, and
467              the partial-line-but-nonblocking case can be distinguished  with
468              the chan blocked command.
469
470       chan names ?pattern?
471              Produces  a  list of all channel names. If pattern is specified,
472              only those channel names that match it (according to  the  rules
473              of string match) will be returned.
474
475       chan pending mode channelId
476              Depending on whether mode is input or output, returns the number
477              of bytes of input or output  (respectively)  currently  buffered
478              internally  for channelId (especially useful in a readable event
479              callback to impose application-specific  limits  on  input  line
480              lengths  to  avoid  a potential denial-of-service attack where a
481              hostile user crafts an extremely  long  line  that  exceeds  the
482              available  memory  to buffer it).  Returns -1 if the channel was
483              not opened for the mode in question.
484
485       chan postevent channelId eventSpec
486              This subcommand is used by command handlers specified with  chan
487              create.  It notifies the channel represented by the handle chan‐
488              nelId that the event(s) listed in the eventSpec  have  occurred.
489              The argument has to be a list containing any of the strings read
490              and write. The list must contain at least one element as it does
491              not  make  sense to invoke the command if there are no events to
492              post.
493
494              Note that this subcommand can only be used with channel  handles
495              that were created/opened by chan create. All other channels will
496              cause this subcommand to report an error.
497
498              As only the Tcl level of a channel, i.e.  its  command  handler,
499              should post events to it we also restrict the usage of this com‐
500              mand to the interpreter  that  created  the  channel.  In  other
501              words, posting events to a reflected channel from an interpreter
502              that does  not  contain  it's  implementation  is  not  allowed.
503              Attempting  to  post  an  event  from any other interpreter will
504              cause this subcommand to report an error.
505
506              Another restriction is that it is not possible  to  post  events
507              that  the  I/O core has not registered an interest in. Trying to
508              do so will cause the method to throw an error. See  the  command
509              handler  method  watch  described in reflectedchan, the document
510              specifying the API of command handlers for reflected channels.
511
512              This command is safe and made accessible to  safe  interpreters.
513              It  can trigger the execution of chan event handlers, whether in
514              the current  interpreter  or  in  other  interpreters  or  other
515              threads,  even where the event is posted from a safe interpreter
516              and listened for by a trusted interpreter. Chan  event  handlers
517              are always executed in the interpreter that set them up.
518
519       chan puts ?-nonewline? ?channelId? string
520              Writes  string to the channel named channelId followed by a new‐
521              line character. A trailing newline character is  written  unless
522              the  optional flag -nonewline is given. If channelId is omitted,
523              the string is written to the standard output channel, stdout.
524
525              Newline characters in the output are translated by chan puts  to
526              platform-specific  end-of-line  sequences  according to the cur‐
527              rently configured value of the -translation option for the chan‐
528              nel  (for  example,  on  PCs newlines are normally replaced with
529              carriage-return-linefeed sequences; see chan configure above for
530              details).
531
532              Tcl  buffers  output internally, so characters written with chan
533              puts may not appear immediately on the output  file  or  device;
534              Tcl  will  normally delay output until the buffer is full or the
535              channel is closed.  You can force output to  appear  immediately
536              with the chan flush command.
537
538              When the output buffer fills up, the chan puts command will nor‐
539              mally block until all the buffered data has  been  accepted  for
540              output  by the operating system.  If channelId is in nonblocking
541              mode then the chan puts command will not block even if the oper‐
542              ating  system cannot accept the data.  Instead, Tcl continues to
543              buffer the data and writes it in the background as fast  as  the
544              underlying  file  or device can accept it.  The application must
545              use the Tcl event loop for nonblocking output to work; otherwise
546              Tcl  never  finds  out that the file or device is ready for more
547              output data.  It is possible for an arbitrarily large amount  of
548              data  to  be  buffered  for a channel in nonblocking mode, which
549              could consume a large amount of memory.  To avoid  wasting  mem‐
550              ory,  nonblocking I/O should normally be used in an event-driven
551              fashion with the chan event command (do  not  invoke  chan  puts
552              unless you have recently been notified via a file event that the
553              channel is ready for more output data).
554
555       chan read channelId ?numChars?
556
557       chan read ?-nonewline? channelId
558              In the first form, the result will be the next numChars  charac‐
559              ters read from the channel named channelId; if numChars is omit‐
560              ted, all characters up to the point when the channel would  sig‐
561              nal  a  failure  (whether an end-of-file, blocked or other error
562              condition) are read. In the second form (i.e. when numChars  has
563              been  omitted) the flag -nonewline may be given to indicate that
564              any trailing newline in the string that has been read should  be
565              trimmed.
566
567              If  channelId  is in nonblocking mode, chan read may not read as
568              many characters as requested: once all available input has  been
569              read,  the command will return the data that is available rather
570              than blocking for more input.  If the channel is  configured  to
571              use a multi-byte encoding, then there may actually be some bytes
572              remaining in the internal buffers that do not  form  a  complete
573              character.   These  bytes  will not be returned until a complete
574              character is available or end-of-file is reached.   The  -nonew‐
575              line  switch  is  ignored if the command returns before reaching
576              the end of the file.
577
578              Chan read translates end-of-line sequences  in  the  input  into
579              newline  characters according to the -translation option for the
580              channel (see chan configure above for a discussion on  the  ways
581              in which chan configure will alter input).
582
583              When  reading  from a serial port, most applications should con‐
584              figure the serial port channel to be nonblocking, like this:
585                     chan configure channelId -blocking 0.
586              Then chan read behaves much like  described  above.   Note  that
587              most  serial ports are comparatively slow; it is entirely possi‐
588              ble to get a readable event for each character read  from  them.
589              Care  must  be  taken  when  using  chan read on blocking serial
590              ports:
591
592              chan read channelId numChars
593                     In this form chan read blocks until  numChars  have  been
594                     received from the serial port.
595
596              chan read channelId
597                     In  this form chan read blocks until the reception of the
598                     end-of-file character, see chan  configure  -eofchar.  If
599                     there  no  end-of-file  character has been configured for
600                     the channel, then chan read will block forever.
601
602       chan seek channelId offset ?origin?
603              Sets the current access  position  within  the  underlying  data
604              stream  for the channel named channelId to be offset bytes rela‐
605              tive to origin. Offset must be an integer (which  may  be  nega‐
606              tive) and origin must be one of the following:
607
608              start     The  new access position will be offset bytes from the
609                        start of the underlying file or device.
610
611              current   The new access position will be offset bytes from  the
612                        current  access  position; a negative offset moves the
613                        access position backwards in the  underlying  file  or
614                        device.
615
616              end       The  new access position will be offset bytes from the
617                        end of the file or device.  A negative  offset  places
618                        the access position before the end of file, and a pos‐
619                        itive offset places the access position after the  end
620                        of file.
621
622              The origin argument defaults to start.
623
624              Chan seek flushes all buffered output for the channel before the
625              command returns, even if the channel is in nonblocking mode.  It
626              also  discards  any  buffered  and  unread  input.  This command
627              returns an empty string.  An error occurs  if  this  command  is
628              applied  to  channels  whose  underlying file or device does not
629              support seeking.
630
631              Note that offset values are byte offsets, not character offsets.
632              Both  chan  seek  and  chan  tell operate in terms of bytes, not
633              characters, unlike chan read.
634
635       chan tell channelId
636              Returns a number giving the current access position  within  the
637              underlying  data  stream  for  the channel named channelId. This
638              value returned is a byte offset that can be passed to chan  seek
639              in order to set the channel to a particular position.  Note that
640              this value is in terms of bytes, not characters like chan  read.
641              The  value returned is -1 for channels that do not support seek‐
642              ing.
643
644       chan truncate channelId ?length?
645              Sets the byte length of the underlying data stream for the chan‐
646              nel  named channelId to be length (or to the current byte offset
647              within the underlying data stream if  length  is  omitted).  The
648              channel is flushed before truncation.
649

EXAMPLE

651       This  opens a file using a known encoding (CP1252, a very common encod‐
652       ing on Windows), searches for a string, rewrites that part,  and  trun‐
653       cates the file after a further two lines.
654
655              set f [open somefile.txt r+]
656              chan configure $f -encoding cp1252
657              set offset 0
658
659              # Search for string "FOOBAR" in the file
660              while {[chan gets $f line] >= 0} {
661                 set idx [string first FOOBAR $line]
662                 if {$idx > -1} {
663                    # Found it; rewrite line
664
665                    chan seek $f [expr {$offset + $idx}]
666                    chan puts -nonewline $f BARFOO
667
668                    # Skip to end of following line, and truncate
669                    chan gets $f
670                    chan gets $f
671                    chan truncate $f
672
673                    # Stop searching the file now
674                    break
675                 }
676
677                 # Save offset of start of next line for later
678                 set offset [chan tell $f]
679              }
680              chan close $f
681

SEE ALSO

683       close(n),   eof(n),   fblocked(n),  fconfigure(n),  fcopy(n),  file(n),
684       fileevent(n), flush(n), gets(n), open(n),  puts(n),  read(n),  seek(n),
685       socket(n), tell(n), refchan(n)
686

KEYWORDS

688       channel, input, output, events, offset
689
690
691
692Tcl                                   8.5                              chan(n)
Impressum