Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

problem with printing to begining of file

Status
Not open for further replies.

calabama

Programmer
Feb 19, 2001
180
US
Hello,
I am trying to make this sub write either to the begining or the end of the file. The variable $placement indicates which process will execute. This variable is then used in the if statement inside the sub routine below.

The print statement print DB "$record\n";
prints to the end of the file. How do I print to the top of the file.

Thanks

Code:
sub add_record {
  $key   = time();
  $record=$key;
  $placement = $q->param('placement');

  foreach $field (@fields){
    ${$field}  = $q->param($field);
    ${$field}  = filter(${$field});
    $record   .= "\::${$field}";
  }

  unless (-e $database){
    open (DB, ">$database") || die "Error creating database.  $!\n";
  } else {
    open (DB, ">>$database") || die "Error opening database.  $!\n";
  }
   flock DB, $EXCLUSIVE;
   seek DB, 0, 2;
       
if ($placement eq "beg") {
} else {  print DB "$record\n";
}

   flock DB, $UNLOCK;
  close(DB);
} 
# End of add_record subroutine.
In the begining
Let us first assume that there was nothing to begin with.
 
You opened a file for appending
so automatically it will be adding to the end.
If you want to add to the top of the file try to read the file first and put it in an array starting from 1, then
in position 0 of your array. After that you can output to the file.

Mtek13
 
Or if the file is too large to read into memory, you could do something like this:
Code:
###########################################

$filepath = "/path/to/file";
$addition = "Some wonderful string here";

addToTop($filepath, $addition) || die "Couldn't add to top";

sub addToTop {
    my $filepath = shift;
    my $string = shift;
    my $bak = ".addToTopBakup";

    rename($filepath, $filepath.$bak) || return 0;
    open( FILE, $filepath.$bak ) || return 0;
    open( UPDATEDFILE, ">".$filepath ) || return 0;

    print UPDATEDFILE $string;
    while(<FILE>){ print UPDATEDFILE $_; }

    close FILE;
    close UPDATEDFILE;

    unlink $filepath.$bak;
}
###########################################

And that's all folks.

--jim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top