Updated 2016-02-10 10:47:39 by HJG

read - Read characters from a channel
read ?-nonewline? channelId
read channelId number-of-characters


Reads a sequence of characters from the specified channel. The read characters are returned as the result of the command.

When the channeId is in blocking mode, if a number-of-characters was specified that many characters will be read (except if EOF is encountered first), and without an exact number of characters to read the command will read everything until it encounters EOF (discarding the last newline if -nonewline is given).

In the case of a non-blocking channel, the read command will try its best to get the specified number of characters or until no more are available when no count is given (in which case the last newline will be discarded if -nonewline is given), but will bail out if the internal buffers of Tcl are empty and the underlying OS structure incapable of delivering more input. When this happens the command will just return the characters it could read; eof and fblocked can be used to determine the reason for a short read.

When Working with binary data make sure the channel was configured with -translation binary. Only then it is allowed to equate characters and bytes.

As is said in tcllib, it's better to "use the [file size] command to get the size, which preallocates memory, rather than trying to grow it as the read progresses."
 read channelId [file size $_filename]

rather than just
 read channelId

Or use the fileutil::cat command instead where this is implemented.

See also