From: Rob Biedenharn Date: 2008-08-25T22:46:22+09:00 Subject: Re: Open file, get first line, delete first line close file On Aug 25, 2008, at 9:21 AM, Erik Hollensbe wrote: > Rob Biedenharn wrote: >> On Aug 25, 2008, at 4:07 AM, Erik Hollensbe wrote: >> >>> Dave Bass wrote: >>>> And... it's a lot easier to delete the *last* line of a file than >>>> the >>>> first. >>> >>> I don't think this is actually true, can you explain further? >>> >>> -Erik >> >> >> You can just truncate the file size. You don't have any subsequent >> lines (bytes) to move into a new position within the file. > > How do you know which line is the last line? > > Unless there's something I don't know, that involves reading the whole > file, or a combination of seek/read from the end until you find the > last > newline, which is essentially what tail +2 does, but starts at the > beginning of the file. > > "Moving" data in a file is the worst possible scenario for I/O at all. > You can do both of these operations in a single pass read of the file > without shoving the whole thing into memory at once. It just involves > writing to one file and reading from another, is all. > -- > Posted via http://www.ruby-forum.com/. Well, if you want/need the last line(s) of a file (presumably text or how would you define a "line"), you can take a look at the File::Tail gem. gem install file-tail I had some Perl code (lifted from some forum or article) that would cut initial lines out of a log file using sysread/syswrite with a truncate to reset the end-of-file. I don't recall if it used a single file descriptor or two separate ones, but the idea is the same -- move bytes "backward" across the gap that you want to eliminate. I agree with your "worst possible scenario for I/O" assessment. -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com