Well, finally found an explanation and a solution: calling fgets()
twice. Because if there's no length limit supplied (and it's not EOF)
when calling the function, it continues reading until it finds the
first newline character. So calling fgets() again will ensure that it
will read from the _beginning_ of the *next* line:

<?php
function getCity($file)
{
   // Try to open the file
   if (!file_exists($file) || !($handle = fopen($file, "r")))
   {
       die('Could not open file for reading.');
   }

   $size = filesize($file);
   $randval = rand(0, $size);

   // Seek to a random position in the file
   fseek($handle, $randval);

   // Get random city name
   $line = trim(fgets($fp, 2048));
   $line = trim(fgets($fp, 2048));

   fclose($fp);

   // If line was empty, try again
   if(empty($line))
   {
       $line = getCity($file);
   }

   return($line);
}
?>

To clarify more, if the first call to fgets() reads the line
containing the city name 'Alexandria', it might be read as:
andria

Now calling fgets() again will definitely read the whole next line:
Dallas


>
> Yes, I agree that that note is complete hogwash, and have just deleted
> it!
>
> Cheers!
>
> Mike
>

Thanks. :)

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to