Search code examples
phpfgetc

fgetc() function to read the whole file


I'm trying to read the whole file using fgetc() with a do..while loop. I know this is not recommended but it should work. The contents of counter.dat are i dont know whta to do but the ouput that I'm getting is 0. Why 0?

<?php
 $f = "counter.dat";
 if (!($fp = fopen($f,"r"))) {
      die("Can Not Open $f");
 }
 do {
  $one_char = fgetc($fp);
  $counter = $one_char;
  $counter .= $one_char;
 } while($one_char);
 fclose($fp);
 $counter = (int) $counter;
 echo $counter;
?>

Solution

  • You're overwriting $counter each time through the loop, before you append to it. And on the last iteration, $one_char will be FALSE, so you're setting $counter = FALSE;, and converting that to an integer returns 0.

    You also need to initialize $counter to an empty string at the beginning.

    Since the file doesn't contain an integer, you shouldn't use (int) $counter. Just print the value of $counter.

    Do it like this:

    $counter = "";
    while ($one_char = fgetc($fp)) {
        $counter .= $one_char;
    }
    echo $counter;
    

    This exits the loop immediately when it gets to EOF, it won't try to use the FALSE value from the last iteration.