note 73503 added to function.fseek

From: Date: Mon, 26 Feb 2007 19:38:50 +0000
Subject: note 73503 added to function.fseek
Groups: php.notes 
Request: Send a blank email to php-notes+get-123906@lists.php.net to get a copy of this message
Here's a function I wrote to binary search for a line of text within a file, particularly useful when the file is too large to read into memory at once and you want a faster search than linear. function binary_search_in_file($filename, $search) { //Open the file $fp = fopen($filename, 'r'); //Seek to the end fseek($fp, 0, SEEK_END); //Get the max value $high = ftell($fp); //Set the low value $low = 0; while ($low <= $high) { $mid = floor(($low + $high) / 2); // C floors for you //Seek to half way through fseek($fp, $mid); if($mid != 0){ //Read a line to move to eol $line = fgets($fp); } //Read a line to get data $line = fgets($fp); if ($line == $search) { fclose($fp); return $line; } else { if ($search < $line) { $high = $mid - 1; } else { $low = $mid + 1; } } } //Close the pointer fclose($fp); return FALSE; } ---- Server IP: 194.145.210.4 Probable Submitter: 87.194.60.192 ---- Manual Page -- http://www.php.net/manual/en/function.fseek.php Edit -- https://master.php.net/note/edit/73503 Del: integrated -- https://master.php.net/note/delete/73503/integrated Del: useless -- https://master.php.net/note/delete/73503/useless Del: bad code -- https://master.php.net/note/delete/73503/bad+code Del: spam -- https://master.php.net/note/delete/73503/spam Del: non-english -- https://master.php.net/note/delete/73503/non-english Del: in docs -- https://master.php.net/note/delete/73503/in+docs Del: other reasons-- https://master.php.net/note/delete/73503 Reject -- https://master.php.net/note/reject/73503 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#123906) next »