This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

Reading last 20 lines from file

Old posts that have not been replied to for several years.
Locked
g
genius3k

Reading last 20 lines from file

Post by genius3k »

What would be the best way to go about reading the last 20 lines from a txt file?

The only thing I can think of is, check how many lines there are, and make it read the last 20 ones. Which involves a calculation for each line read...problem is - I'm not able to put it into code. Does anybody know a way to do this...or even a better way to read last 20 lines?

Thanks, later.
e
egghead
Master
Posts: 481
Joined: Mon Oct 29, 2001 8:00 pm
Contact:

Re: Reading last 20 lines from file

Post by egghead »

genius3k wrote:What would be the best way to go about reading the last 20 lines from a txt file?

The only thing I can think of is, check how many lines there are, and make it read the last 20 ones. Which involves a calculation for each line read...problem is - I'm not able to put it into code. Does anybody know a way to do this...or even a better way to read last 20 lines?

Thanks, later.
If your file is not too big, you can use a simple procedure.

- [read] in the complete file at once
- [split] the file into a list around the newline character
- take the last 20 elements of that list

done.
O
Ofloo
Owner
Posts: 953
Joined: Tue May 13, 2003 1:37 am
Location: Belguim
Contact:

Post by Ofloo »

Code: Select all

proc readLines {f n} {
  if {![catch {open $f r} rf]} {
    set c [read $rf]
    set l [expr ([llength $c] - $n]) - 1];# i think llength includes 0 so..
    if {$l <= 0} {
      foreach x [split $c \n] {
        puts $x
      }
      close $rf
      return 
    }
    foreach x [split $c \n] {
      if {[info exists i]} {
        incr i
      } else {
      	set i 0
      }
      if {($i >= $l)} {
        puts "$x"
      }
    }
    close $rf
  } else {
    error "Couldn't open $f.."
  }
}

readLines <yourfile> <20>
i think this works haven't tested it tho
XplaiN but think of me as stupid
Locked