note 69000 added to function.fseek

From: Date: Sat, 19 Aug 2006 00:35:01 +0000
Subject: note 69000 added to function.fseek
Groups: php.notes 
Request: Send a blank email to php-notes+get-116051@lists.php.net to get a copy of this message
Jim's (jim at lfchosting dot com) code for the last-line issue is perfect if the file is not empty, or moreover if it has more than one line. However if the file you're using cotains no new-line character at all (i.e. it is empty or it's got one line and only one) the while loop will stuck indefinitely. I know this script is meant for big files which would always contain at least several lines, but it would be clever to make the script error-proof. Thus, here's a little modification to his code. <?php function readLastLine ($file) { $fp = @fopen($file, "r"); $pos = -1; $t = " "; while ($t != "\n") { if (!fseek($fp, $pos, SEEK_END)) { // *** - fseek returns 0 if successfull, and -1 if it has no succes as in seeking a byte outside the file's range $t = fgetc($fp); $pos = $pos - 1; } else { // *** rewind($fp); // *** break; // *** } // *** } $t = fgets($fp); fclose($fp); return $t; } ?> Lines added and/or modified have been marked with "// ***". I hope this helps! Regards! ---- Server IP: 200.59.45.3 Probable Submitter: 200.115.204.78 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/function.fseek.php Edit -- https://master.php.net/note/edit/69000 Del: integrated -- https://master.php.net/note/delete/69000/integrated Del: useless -- https://master.php.net/note/delete/69000/useless Del: bad code -- https://master.php.net/note/delete/69000/bad+code Del: spam -- https://master.php.net/note/delete/69000/spam Del: non-english -- https://master.php.net/note/delete/69000/non-english Del: in docs -- https://master.php.net/note/delete/69000/in+docs Del: other reasons-- https://master.php.net/note/delete/69000 Reject -- https://master.php.net/note/reject/69000 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#116051) next »