Usamah M. Ali wrote:
> 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.

fseek doesn't go to the start of a line, it goes to a particular byte -
so that's where the problem lies (not with fgets). There's no function
(that I could see) which would go to the start of the line based on that
offset (I guess you could fseek to a particular spot then reverse char
by char until you find a newline - but that'll be rather slow for
anything that has a long line).


You could read the whole thing into an array and do a rand on that:

$cities = file('filename.txt');

// take 1 off from the max number as $cities is a 0 based array
$number_of_cities = sizeof($cities) - 1;

$city_number = rand(0, $number_of_cities);
$city = $cities[$city_number];

Though if you have a big file that reads the whole thing into memory etc.

-- 
Postgresql & php tutorials
http://www.designmagick.com/

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

Reply via email to