http://qs321.pair.com?node_id=119037


in reply to Re: Re: How do I add a few stings of text, 30 lines before the EOF? (update)
in thread How do I add a few stings of text, 30 lines before the EOF?

Knowing exactly what byte location you want to insert at, you can seek to that location, read in the final bytes of the file, go back to that location and write out the new lines and the final bytes. To give some code:

use Fcntl qw(:seek :flock); # get constants # location suitable for direct use in seek. use constant INSERT_LOCATION => (-947, SEEK_END); my $file = "..."; # open the file for update open FILE, "+<$file" or die "couldn't open $file: $!\n"; # don't have two copies of us update the file at the # same time... flock FILE, LOCK_EX or die "flock: $!\n"; # go to our location seek FILE, INSERT_LOCATION or die "seek: $!\n"; # read the rest of the file from there my $end = do { local $/; <FILE> }; defined $end or die "read: $!\n"; # go back to our location seek FILE, INSERT_LOCATION or die "seek: $!\n"; # write new data followed by old data from that point. print FILE $newlines, $end or die "print: $!\n"; close FILE or warn "close: $!\n";

(I'm being incredibly paranoid by checking the return value of print and readline and close. You probably don't have to be.)

Be forewarned that if the byte location is or becomes wrong then file curruption is likely.

  • Comment on Re: Re: Re: How do I add a few stings of text, 30 lines before the EOF? (update)
  • Download Code