Reputation: 3103
let's say I have a filehandle. Is there a way for me to know the name of the file it is writing to? I.e., you usually use:
set fh [ open "fname" "w" ]
I want a proc that would have the output:
puts [ getFHFName $fh]
>fname
Any ideas?
Upvotes: 1
Views: 762
Reputation: 137787
Tcl doesn't provide any built-in mechanism to provide that. (It'd be something you could find out with fconfigure
if we did do it… but it isn't.)
The easiest workaround is to keep a global array that maps from file handles to filenames. You can either keep this yourself, or you can override open
and close
to maintain the mapping.
rename open _open
rename close _close
array set fhmap {}
proc open {filename args} {
global fhmap
set fd [_open $filename {*}$args]
# Note! Do not normalise pipelines!
if {![string match |* $filename]} {
set filename [file normalize $filename]
}
set fhmap($fd) $filename
return $fd
}
# Probably ought to track [chan close] too.
proc close {filehandle args} {
global fhmap
# Note that we use -nocomplain because of sockets.
unset -nocomplain fhmap($filehandle)
tailcall _close $filehandle {*}$args
}
proc getFHFName {filehandle} {
global fhmap
return $fhmap($filehandle)
}
Upvotes: 3