Say there is a file log.txt
and some kind of log is being appended to it permanently.
I want to track that file in the TCL environment.
I have tried this but it didn't worked.
set log [open log.txt a]
for { } { true } { update; after 1000 } {
# expected to get here the appended part
read $log
seek $log 0 end
}
Is it possible to read the modified file by the same file handle log
, or I have to close and re-open the file log.txt
?
Is there a kind of equivalent of Linux command tail -f
in TCL ?
-- reading a file. The Tcl file commands are file, open, close, gets and read, and puts, seek, tell, and eof, fblocked, fconfigure, Tcl_StandardChannels(3), flush, fileevent, filename. One way to get file data in Tcl is to 'slurp' up the file into a text variable.
Tcl supports file handling with the help of the built in commands open, read, puts, gets, and close. A file represents a sequence of bytes, does not matter if it is a text file or binary file.
When you have installed Tcl, the program you will then call to utilize it is tclsh . For instance, if you write some code to a file "hello. tcl", and you want to execute it, you would do it like so: tclsh hello.
You can run this program by starting tclsh from the start menu, then typing the command source c:/hello. tcl.
Just use tail
. It knows more that you about how to handle complicated cases (you can look at its source).
In one of my projects, I have something like this to monitor a trace file produced by a proprietary tool:
set fd [open [list | tail --follow=name --retry --lines 0 $opt(trace) 2>@1]]
chan event $fd readable [list FollowTrace $fd]
proc FollowTrace fd {
if {[gets $fd line] < 0} {
set code [catch {close $fd} err]
if {$code == 0} {
set ::result 0
} else {
puts stderr $err
set ::result 1
}
return
}
switch -regexp -matchvar parts -- $line {
{Tm_Session::Open.*FileName=([^,]+)} {
TryMakeLock [FullPathname [lindex $parts 1]]
}
{Tm_Session::Close.*FileName=([^,]+)} {
StartUpload [lindex $parts 1]
}
}
}
The general idea is that you spawn tail
on a given file then enter event loop and process tail
's output line-by-line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With