How to track a log file in TCL

By : Vahagn
Source: Stackoverflow.com
Question!

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 ?

By : Vahagn


Answers

You're not far off, just a few things to fix:

  1. In this code you are reading from the file, not appending to it, some other process will be doing that, so should open the file in read mode, not append mode, ie. drop the "a" option from the open command.
  2. You should only seek to the end of the file once, before you start reading, otherwise you will be skipping stuff that gets added later, so move the seek command ahead of the loop.
  3. In the code posted, you are not doing anything with the text that you read - I'll give an example of just writing it back to stdout.
  4. You only need the update command if your processing within the loop involves updating a gui or something else that requires the event loop - it's not needed for the code posted. Altogether this gives:

    set log [open log.txt]
    seek $log 0 end
    
    for { } { true } { after 1000 } {
    
        # expected to get here the appended part
        puts -nonewline [read $log]
    }
    


I have managed to write tail -f equivalent on pure Tcl. The code is below:

proc readHandler {handle} {
    puts -nonewline [read $handle]
    flush stdout
    # to reduce CPU overhead...
    after 1000
}

set hFile [open "file.log" "r"]
# seek to the end of file if needed
# seek $hFile 0 end 

fconfigure $hFile -buffering none -eofchar "" -blocking no
fileevent $hFile readable [subst {readHandler $hFile}]

#just for exiting into main event loop
vwait forever
By : GrAnd


This video can help you solving your question :)
By: admin