#!/usr/bin/perl -w { # copies from stdin into user-specified existing file, overwriting contents. # Key idea is the "into"; having pre-allocated space for, say, an error file, # is very handy in case of problems running out of disk space. # If more is written than was preallocated, file is extended if possible. If # less is written, file size is reset to what was written # Uses "perl library" function CGiDie for abnormal terminations # Note based on observation on globec (Solaris): although "stderr files" (targets after # 2> on command line) are shell-created before "the program" starts to run, if stderr is # piped someplace, the pipe target process is NOT created at that time (hypothesis is that # it's created "when needed" - hypothesis not confirmed) $version = $0 . " version 1.0 Sep 3 2011"; # Arg 1 - output file name (required) ($outfile,$dummy) = @ARGV; (defined $dummy) && &quit ("Too many arguments"); (defined $outfile) || &quit ("Required file name argument missing"); # Avoid issues about ARGV being taken as a stdin list of file specs undef @ARGV; (open HANDLE,"+< $outfile") || &quit ("Failed to open file $outfile. Reason: $!"); (seek HANDLE,0,0) || &quit ("Failed to reposition file pointer in file $outfile. Reason: $!"); $nrec = $nbytes = 0; while (<>) { $nrec++; $nbytes += length; (print HANDLE $_) || &quit ("Failed to write record number $nrec into file $outfile. Reason: $!"); } (truncate HANDLE,$nbytes) || &quit ("Failed to set file $outfile to its used length ($nbytes). Reason: $!"); (close HANDLE) || &quit ("Failed to close file $outfile. Reason: $!"); $nrec || (unlink $outfile) || &quit ("Failed to remove un-written-into file $outfile. Reason: $!"); exit 0; } sub quit { $message = " *** " . $_[0] . "\nThis message issued " . localtime() . "\n$version\n"; ### &CgiDie ($message); die ($message); }