Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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

by wog (Curate)
on Oct 16, 2001 at 04:32 UTC ( #119037=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://119037]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2022-12-09 23:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?