Posted to tcl by kap at Tue Oct 28 00:30:45 GMT 2014view pretty

oo::class create redirect {
    variable File
    constructor {filename} {
        set File [open $filename w]
    }
    method initialize {handle mode} {
        if {$mode ne "write"} {error "can't handle reading"}
        return {finalize initialize write}
    }
    method finalize {handle} {
    }
    method write {handle data} {
        puts $File $data
    }
    destructor {
        catch {close $File}
    }
}    

# Redirect stdout to file
chan push stdout [redirect new foo.txt]
chan configure stdout -buffering none

# Test
puts 1
puts 2
puts 3
puts -nonewline a
puts -nonewline b
puts -nonewline c