Roman Kaganovich
Roman Kaganovich

Reputation: 658

how to check that file is closed

How can I check that file is closed?

For example:

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

Now I want to check that channel $fh is closed The command:

file  channels $fh

return nothing so I cannot use it in any condition.

Upvotes: 1

Views: 1806

Answers (3)

kostix
kostix

Reputation: 55453

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.

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246807

You could also use something like:

proc is_open {chan} {expr {[catch {tell $chan}] == 0}}

Upvotes: 2

patthoyts
patthoyts

Reputation: 33203

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

Upvotes: 2

Related Questions