eof

eof a build-in command, checks for an end-of-file condition on a channel. The name is an acronym for End Of File.

The same as chan eof.

See Also

Frequently-Made Mistakes in Tcl ,by Cameron Laird
Describes a common [eof] mistake
fblocked
detect whether a read operation exhausted all available input

Documentation

official reference

Synopsis

eof channelId

Description

[eof] is used to determine whether the channel has reached the end of input.

Returns 1 if an end of file condition occurred during the most recent input operation on channelId (such as gets), 0 otherwise.

ChannelId must be an identifier for an open channel such as a Tcl standard channel (stdin, stdout, or stderr), the return value from an invocation of open or socket, or the result of a channel creation command provided by a Tcl extension.

When [eof] is true for a socket channel, it's time to close that socket.

[eof] is only true after no more characters can be read from the channel, so usually you'll want to first try to read the channel, and if you only get back the empty, use [eof] to determine whether you've reached the end of the channel:

while 1 {
        if {[gets $chan line] > 0} {
                #do stuff
        } else {
                if {[eof $chan]} {
                        close $chan
                        break
                } else {
                        #haven't reached the end of a non-blocking channel
                        #give it a moment
                        after 20 
                }
        }
}

instead of

#warning! Bad Code!
while {![eof $fp]} {
   gets $fp line
   if [eof $fp] break ;# otherwise loops one time too many
   ...
} ;# RS  

Another alternative:

gets $fp line
while {![eof $fp]} {
    # process line
    gets $fp line
}

Also, gets returns -1 when it encountered an EOF. Hence, I now always write:

while {[gets $fp line] >= 0} {
    ...
}
close $fp