Reply to Re: Select a random line from a text file

Your name:

Reply:


Posted by NC on 09/28/92 11:41

CORRECTION: Instead of fread(), you should use fgets().
Sorry for the confusion... The correct sequence of steps is:

1. Determine file size with filesize().
2. Select a random number between 0 and file size with rand().
3. Open the file for reading with fopen().
4. Go to the byte with the number randomly selected in Step 2
with fseek().
5. Read a line with fgets(); if fgets() returns FALSE, rewind()
and fgets() again.
6. The line read in Step 5 is most likely incomplete, so you
need to read another line with another fgets(); again, if
fgets() returns FALSE, rewind() and fgets() again.

NC wrote:
>
> The fastest way I can think of is this:
>
> 1. Determine file size with filesize().
> 2. Select a random number between 0 and file size with rand().
> 3. Open the file for reading with fopen().
> 4. Go to the byte with the number randomly selected in Step 2
> with fseek().
> 5. Read a line with fread(); if fread() returns FALSE, rewind()
> and fread() again.
> 6. The line read in Step 5 is most likely incomplete, so you
> need to read another line with another fread(); again, if
> fread() returns FALSE, rewind() and fread() again.
>
> The line read in Step 6 is the random line you seek...
>
> Cheers,
> NC

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация