I looked and did not find any way to get file name from handle, so I created my own solution. This solution uses the trace command to catch when the open command exits. At which time, both file names and handles are available, so I associate them to each other via the global fileNameFromHandle array.
# This script demonstrate the use of the trace command to keep track
# the relationship between file handles and file names
# ======================================================================
# Setup trace to track file handle vs. file name
array set fileNameFromHandle {}
proc trace_proc {command code result op} {
if {$code != 0} return; # Ignore failed calls
set filename [lindex $command 1]; # command = {open filename mode}
set filehandle $result
set ::fileNameFromHandle($filehandle) $filename
}
proc getFileName {handle} { return $::fileNameFromHandle($handle) }
trace add execution open leave trace_proc
# ======================================================================
# Main
set handle1 [open file1.txt r]
# Do something with the files
# Need filename from handle?
puts "Handle: $handle1, filename: [getFileName $handle1]"
close $handle1
Update
I don't have Tcl 8.0.5, to verify if this solution works. Please try it out and let me know. You can also trace the close command to remove the association.