how do i read only the last line of a file ??
or beter yet how do i get the last line of a file (txt)
Code: Select all
proc read_last_line {fname} {
set fp [open $fname r]
set pos 512
while {1} {
seek $fp -$pos end
set data [read -nonewline $fp]
set lines [split $data \n]
if {[llength $lines] > 1} {
close $fp
return [lindex $lines end]
} elseif {[tell $fp] >= $pos} {
close $fp
return $data
}
incr pos 512
}
}
Code: Select all
proc read_last_line {fname} {
set fp [open $fname r]
# pos is the position in the file (in reverse)
# we start at 512 bytes from the end of the file
set pos 512
while {1} {
# this moves to $pos bytes before the end of the file
seek $fp -$pos end
# read to the end of the file
set data [read -nonewline $fp]
# we may have read multiple lines (if less than 512 bytes)
set lines [split $data \n]
if {[llength $lines] > 1} {
# yup, we read at least 1 line and part of another, so we know
# we for sure have the complete last line, we're done
close $fp
return [lindex $lines end]
} elseif {[tell $fp] < $pos} {
# Well, before I had >=, but it should be <.
# This happens if the entire file is < 512 bytes, and we didn't read
# in multiple lines... therefore the file is a single line and we read the
# whole thing, so we're done.
close $fp
return $data
}
# Now we just repeat the process, adding another 512 bytes
incr pos 512
}
}