Re: A problem with fgets()

From: Date: Fri, 30 May 2008 01:05:53 +0000
Subject: Re: A problem with fgets()
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-274851@lists.php.net to get a copy of this message
On Fri, May 30, 2008 at 3:38 AM, Chris <dmagick@gmail.com> wrote: > 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. > I didn't say fseek() goes to the start of a line. I said that fgets() should read a whole line, no matter where the pointer is at. I've already managed to get the result I want by using file() as you've suggested and array_rand(), and the result is very good. I just need to figure out why when using fgets() with fseek() & rand(), the script returns partial strings form the city names. Regards, Usamah

« previous php.general (#274851) next »