note 95413 deleted from function.fread by cmb

From: Date: Sun, 12 Jan 2020 08:21:41 +0000
Subject: note 95413 deleted from function.fread by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-213851@lists.php.net to get a copy of this message
Note Submitter: Tblue ---- 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; } ?>

« previous php.notes (#213851) next »