note 95413 added to function.fread

From: Date: Sat, 02 Jan 2010 01:29:00 +0000
Subject: note 95413 added to function.fread
Groups: php.notes 
Request: Send a blank email to php-notes+get-164530@lists.php.net to get a copy of this message
Note that fread() returns an empty string if you try to read beyond EOF, while the manual states otherwise ("Returns [...] FALSE on failure."). This e. g. happens with empty files (0 bytes long). This does not look like a bug in PHP's fread() implementation to me, but rather like a documentation bug. The manpage for the C function fread() states: > fread() does not distinguish between end-of-file and error, and callers must use feof(3) and > ferror(3) to determine which occurred. It also says: > If an error occurs, or the end-of-file is reached, the return value is a short item count (or > zero). That means that in the case of empty files, C's fread() returns 0 and thus we get an empty PHP string: PHP's fread() does not seem to check for errors as the manpage recommends; that's fine, the PHP programmer has to do it, but it would be nice if this behaviour would be explicitly documented. In short: When using fread(), you have to check for FALSE and empty strings. Consider the following wrapper function: <?php function my_fread( $handle, $length ) { if( ( $ret = fread( $handle, $length ) ) === '' ) { return false; } return $ret; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 84.190.224.121 ---- Manual Page -- http://www.php.net/manual/en/function.fread.php Edit -- https://master.php.net/note/edit/95413 Del: integrated -- https://master.php.net/note/delete/95413/integrated Del: useless -- https://master.php.net/note/delete/95413/useless Del: bad code -- https://master.php.net/note/delete/95413/bad+code Del: spam -- https://master.php.net/note/delete/95413/spam Del: non-english -- https://master.php.net/note/delete/95413/non-english Del: in docs -- https://master.php.net/note/delete/95413/in+docs Del: other reasons-- https://master.php.net/note/delete/95413 Reject -- https://master.php.net/note/reject/95413 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#164530) next »