【问题标题】:get the file name from the file handle value从文件句柄值中获取文件名
【发布时间】:2017-08-24 14:05:29
【问题描述】:

假设我有一个文件句柄。有没有办法让我知道它正在写入的文件的名称? 即,您通常使用:

set fh [ open "fname" "w" ]

我想要一个有输出的 proc:

puts [ getFHFName $fh]
>fname

有什么想法吗?

【问题讨论】:

标签: tcl filehandle


【解决方案1】:

Tcl 没有提供任何内置机制来提供它。 (如果我们确实这样做了,您可以通过 fconfigure 找到它……但事实并非如此。)

最简单的解决方法是保留一个从文件句柄映射到文件名的全局数组。您可以自己保留它,也可以覆盖 openclose 以维护映射。

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)
}

【讨论】:

  • 一个相当晚的回复,我希望避免做这样的事情,并让语言为我处理它。我可以建议将这种机制添加到 TCL 9 中吗?我还可以编写一个文件句柄类,这也应该完成相同的功能。
猜你喜欢
  • 2011-03-19
  • 1970-01-01
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多