ファイルが閉じていることを確認するにはどうすればよいですか?
例えば:
set fh [open "some_test_file" "w"]
puts $fh "Something"
close $fh
ここで、チャネル$ fhが閉じていることを確認します。コマンド:
file channels $fh
何も返さないので、どのような状態でも使用できません。
ファイルが閉じていることを確認するにはどうすればよいですか?
例えば:
set fh [open "some_test_file" "w"]
puts $fh "Something"
close $fh
ここで、チャネル$ fhが閉じていることを確認します。コマンド:
file channels $fh
何も返さないので、どのような状態でも使用できません。
If the close command did not return an error, then it was successful. The file channels
command doesn't take an argument but just returns all the open channels so $channel in [file channels]
would be a redundant test to ensure that you closed the channel. However, how about believing the non-error response of the close command?
I must correct myself - a bit of checking and it turns out the file channels command can take an optional pattern (a glob expression) of channels names to return. So the original example will work if the file is still open. You can test this in a tclsh interpreter using file channels std*
. However, the close command will still return an error that can be caught if it fails to close the channel which would also allow you to potentially handle such errors (possibly retry later for some).
You could also use something like:
proc is_open {chan} {expr {[catch {tell $chan}] == 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.