1

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?

user1134991
  • 3,003
  • 2
  • 25
  • 35
  • Does this answer your question? [Can I find a filename from a filehandle in Tcl?](https://stackoverflow.com/questions/9486361/can-i-find-a-filename-from-a-filehandle-in-tcl) – betontalpfa Apr 08 '21 at 14:31

1 Answers1

3

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)
}
Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
  • A rather belated reply, I was hoping to avoid doing something like this, and have the language handle it for me. May I suggest that such mechanism be added to TCL 9? I can also write a class of filehandle, and this should also get the same functionality done. – user1134991 Apr 10 '21 at 14:37