Page 2 of 2

Posted: Fri Nov 26, 2004 10:15 pm
by Christopher
I wrote this class recently, but never got around to adding file locking. I would love it if some smart programmer could add the file locking part. The one good thing about this code is that it is compatible with Perl::Counter so can be used with Perl scripts and share the counter file.

Code: Select all

class PerlCounter {
var $header = "#COUNTER-1.0\n";

function increment($filename) {
  $offset = strlen($this->header);
  $counter = 0;
	
  $fp = fopen($filename, 'r+');
			
  if ($fp) {
	$contents = fread($fp, filesize($filename));
	if ($contents) {
		$counter = intval(trim(substr($contents, $offset)));
	}
	++$counter;
	$contents = "{$this->header}$counter\n";
	rewind($fp);
	fwrite($fp, $contents);
        ftruncate($fp, strlen($contents));
	fclose($fp);
  }
  return $counter;
}

} // end class