# countf.pl - a library file that defines the function countf. 
# countf is a counter function with read/write file locking.
# Usage: $count = &countf("file"), where file is the path of the
# text file containing the count as its first line
# NB: The flock function is not implemented in NTPerl or MacPerl.
# Copyright 1996 by Stephen Lines (spraxlo@ai.mit.edu)

sub countf {
  die("$0 called countf w/o a filename\n") unless my ($cFile) = @_;
  my $count;                      # Localize count to this function
  if (open(FILE, "+<$cFile")) {   # Open countFile for reading and writing
    flock( FILE, 2);              # 2 means exclusive lock
    $count = <FILE>;              # count = first line of FILE, a string
    $count = $count + 1;          # Increment the count & convert to a number
    seek(  FILE, 0, 0);           # Rewind to beginning of FILE
    print  FILE $count, "\n";     # Write incremented count to FILE
    flock( FILE, 8);              # 8 means release lock
    close( FILE );                # Close right after unlocking
  } else {                        # Don't try to create file, just die!
    die("$0: error opening $cFile for read/write ($!)"); 
  }    # NB: The server shouldn't be able to create files in your directories
  $count;                         # Return the count
}

1; # This statement is here to make "require 'countf.pl';" work.

