A problem with fgets()

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hello,

I have a function that picks up a random entry from a file consisting
of city names, each name on a separate line. The random value is
generated by rand() before fseek()ing to the position determined by
it. The problem is that when using fgets() to get a random line, it
returns a part of the city name, not the whole name. AFAIK, fgets()
reads a whole line, and even if it's in the middle of a line, it reads
the whole next line.

Some sample of the city names file is as follows:

Amsterdam
Zurich
Alexandria
Dallas
Rome
Berlin

And the scripts outputs them weirdly enough something like:
Amster
andria
Da
me
Berlin

Here's the function:

<?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));

    fclose($fp);

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

    return($line);
}
?>

I'm using XAMPP on Windows, PHP 5.2.1.

What am I missing here?

Regards,
Usamah

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


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux