chan copy
Copies the data of one channel to another.
chan copy IN OUT ?-size SIZE? ?-command SCRIPT?
Description
Reads IN to its end, or SIZE bytes, and writes the data to OUT. With no -command it waits for the end and gives the count of bytes. With -command it copies in the background and calls SCRIPT with the count when it ends, which needs the event loop.
Arguments
| Argument | Type | Default | Description |
|---|---|---|---|
| IN | channel | required | The channel to read. |
| OUT | channel | required | The channel to write. |
Options
| Option | Type | Default | Summary |
|---|---|---|---|
-size | integer | -1, no limit | The most bytes to copy. |
-command | command prefix | none | Copies in the background and calls a script at the end. |
-size SIZE
The most bytes to copy.
Copies at most SIZE bytes. A negative SIZE copies to the end of IN.
% set in [open a.txt]; set out [open c2.txt w]
> set n [chan copy $in $out -size 3]
> chan close $in; chan close $out
> list $n [file size c2.txt]
3 3% set in [open a.txt]
> catch {chan copy $in stdout -size x} m
> chan close $in
> error $m
expected integer but got "x"
-errorcode NONE-command SCRIPT
Copies in the background and calls a script at the end.
The copy runs in the event loop, and at its end the event loop calls SCRIPT with the count of bytes, and an error message as a second argument when the copy failed.
% set in [open a.txt]; set out [open d.txt w]
> chan copy $in $out -command {set ::done}
> vwait ::done
> chan close $in; chan close $out
> list $::done [file size d.txt]
6 6Each script is valid, and an error of SCRIPT goes to the handler of background errors.
Returns
The count of bytes, or an empty string with -command.
Examples
% set f [open a.txt w]; chan puts $f hello; chan close $f
> set in [open a.txt]; set out [open c.txt w]
> set n [chan copy $in $out]
> chan close $in; chan close $out
> list $n [file size c.txt]
6 6
Errors
% chan copy nochan stdout
can not find channel named "nochan"
-errorcode TCL LOOKUP CHANNEL nochan
% set in [open a.txt]
> catch {chan copy $in stdout -bogus 1} m
> chan close $in
> error $m
bad option "-bogus": should be -size or -command
-errorcode NONE
Facts
- Capability
channels. A new interpreter does not have it until the host turns it on.- Tcl release
- Tcl 9.1 and 8.6.
- Since
- ztcl 1.0.0-beta.1