Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

How do you write to the middle of a file?

by Anonymous Monk
on Jan 31, 2000 at 06:13 UTC ( #2608=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a file I am using on my website, and I want to go in, at a specified spot, and change|add info to that spot. Is there an easier way besides writing to a temp file, then renaming the temp file over the old file? Thanks
  • Comment on How do you write to the middle of a file?

Replies are listed 'Best First'.
Re: How do you write to the middle of a file?
by devslashneil (Friar) on Jun 13, 2003 at 00:54 UTC
    #!/usr/bin/perl use Tie::File; my $filename = 'foo.dat'; tie @array, 'Tie::File', $filename or die "Cannot open $filename\n"; @array[5] = "Hello, World!\n";
Re: How do you write to the middle of a file?
by Anonymous Monk on Feb 11, 2000 at 23:06 UTC
    Such is the evil of the standard (read UNIX) file model. One solution is as follows:
    $flen = -s $file; # file length in bytes $from = 42; # insertion point open FILE, '+<the/file.ext' or die "Couldn't open file: $!"; read FILE, $buf, ($flen - $from), $from; seek FILE, $from, 0; print FILE 'blahblahblah', $buf;

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2021-04-21 12:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?