Problem with fgets

My php classes was trying to build a counter in PHP using a file (it’s from a book). The problem we are running into is that if we place 0 into the file, it will not get the file. Can anyone suggest a way around this???

This is the code

<?php $ctfile='ctr.txt'; $FILEH = fopen($ctfile, 'r+') or die ("Cannot open $ctfile"); flock($FILEH, LOCK_EX) or die ("Cannot lock file $ctfile"); $ctr=fgets($FILEH) or die ("Cannot get $ctfile"); $ctr= rtrim($ctr, 'n'); if (is_numeric($ctr)) { $count=$ctr +1; rewind($FILEH); $ret=fputs($FILEH, $count); print "$count"; } else { print "error: ctr-$ctr <= not a numeric value"; } fclose ($FILEH); ?>

I presume that you mean an EMPTY file when you said that you put 0 in it.

I think you need to look at http://us3.php.net/manual/en/function.feof.php
Whenever dealing with reading (or writing) files, you need to know where the end of file (EOF) is.

If you open a file and try to do a read on it and it’s empty (thus at the EOF) you will get an error.

while (!feof($file)) {
  do something
}

fclose($file);
Sponsor our Newsletter | Privacy Policy | Terms of Service