SPUG: how to add text at start of a already existing file

Yitzchak Scott-Thoennes sthoenna at efn.org
Tue Jan 18 04:20:17 PST 2005

On Tue, Jan 18, 2005 at 05:08:35PM +0550, Sachin Chaturvedi wrote:
> hi i want to add text at very start of already existing file.
> i have tried this code but it is adding only at end
> open(FH,">>" . $file)or die " can not open \n";
> seek FH,0,0 ;
> print FH $msg . "\n" ;
> close FH or die " i can not close \n";
> i had tried sysopen(FH,$file,O_APPEND|O_WRONLY)
> sysseek FH,0,0
> but it is doing same as said above

Any time you use O_APPEND or >>, anything you write will be put
at the end of the file regardless of what your position in the
file was.

You use open(FH,"+< $file") to open an existing file for reading
and writing.  Then you need to read in the entire current content
of the file, because when you write your $msg out, it will overwrite
what's there already.  After printing $msg, then print the original
file data.  So:

open(FH,"+< $file") or die "could not open: $!\n";
seek FH, 0, 0;
my $content = do { local $/; <FH> }; # read in whole file
seek FH, 0, 0;
print FH $msg, $content;
close FH or die "could not close: $!\n";

More information about the spug-list mailing list