Posted to tcl by thomas at Thu Nov 03 21:45:43 GMT 2011view raw
- set fileToRead d:/tmp/log.txt
- set pollIntervalInMs 1000
- # Get and store the current size of the file to read :
- set waitForFile 1
- while { $waitForFile } {
- if { [catch {
- set lastKnownFileSize [file size $fileToRead]
- } errorMsg] } {
- puts "Warning : Could not get the initial size of $fileToRead. Retry in $pollIntervalInMs ms..."
- after $pollIntervalInMs
- } else {
- set waitForFile 0
- }
- }
- # Store the initial file pointer position (end of file) :
- set currentPos $lastKnownFileSize ; # Can be forced to 0 is a full log file parse operation is required @ startup (but this could take a long time)
- # Loop until a condition is set :
- set continueFlag 1 ; # Set to 0 by a depressed button ?
- while { $continueFlag } {
- # Wait between each poll :
- after $pollIntervalInMs
- # Get the new file size :
- if { [catch {
- set newFileSize [file size $fileToRead]
- } errorMsg ] } {
- puts "Warning : Could not get the size of $fileToRead !"
- continue
- }
- # Has file been modified ? :
- if { $newFileSize != $lastKnownFileSize } {
- # Store file size for next change detection :
- set lastKnownFileSize $newFileSize
- # Try to open file :
- if { [catch {
- set fileHandler [open $fileToRead r]
- } errorMsg ] } {
- puts "Warning : Could not open $fileToRead for reading after change detection ($errorMsg) !"
- continue
- }
- # Deal with the 'truncated' file case :
- if { $newFileSize < $currentPos } {
- puts "Warning : File truncated, moving to the end of file."
- set currentPos $newFileSize
- }
- # Move to the last "known" position :
- if { [catch {
- seek $fileHandler $currentPos start
- } errorMsg] } {
- puts "Warning : Could not seek file $fileToRead to byte $currentPos ($errorMsg) !"
- continue
- }
- # Read until the end of file :
- if { [catch {
- while { [gets $fileHandler line] >= 0 } {
- puts -($currentPos)->$line
- }
- } errorMsg] } {
- puts "Warning : Could not read data from $fileToRead ($errorMsg) !"
- }
- # Store current position and close file :
- if { [catch {
- set currentPos [tell $fileHandler]
- close $fileHandler
- } errorMsg] } {
- puts "Warning : Could not properly close $fileToRead ($errorMsg)"
- }
- }
- }