1

如何检查该文件是否已关闭?

例如:

set fh [open "some_test_file" "w"]
puts $fh "Something"
close $fh

现在我想检查通道 $fh 是否已关闭命令:

file  channels $fh

什么都不返回,所以我不能在任何情况下使用它。

4

3 回答 3

2

如果关闭命令没有返回错误,那么它是成功的。该file channels命令不带参数,而只返回所有打开的通道,因此$channel in [file channels]将是一个冗余测试,以确保您关闭了通道。但是,相信 close 命令的非错误响应怎么样?

我必须纠正自己 - 进行一些检查,结果发现文件通道命令可以采用通道名称的可选模式(全局表达式)来返回。因此,如果文件仍处于打开状态,则原始示例将起作用。您可以在 tclsh 解释器中使用file channels std*. 但是,如果关闭通道失败,close 命令仍将返回一个可以捕获的错误,这也允许您处理此类错误(可能稍后重试某些错误)。

于 2012-10-29T12:20:21.363 回答
2

你也可以使用类似的东西:

proc is_open {chan} {expr {[catch {tell $chan}] == 0}}
于 2012-10-29T14:08:02.057 回答
0

Why not put the channel name into a variable, make the closing code unset that variable, if [close] suceeded and in the checking code just check the variable does not exist (that is, unset)?

Note that I'm following a more general practice found in system programming: once you closed an OS file handle, it became invalid and all accesses to it are hence invalid. So you use other means to signalizing the handle is no more associated with a file.

于 2012-10-31T08:20:09.817 回答