note 51125 added to function.fgets
| From: | Allen at osu1 dot php dot net | Date: | Mon, 21 Mar 2005 01:35:19 +0000 |
| Subject: | note 51125 added to function.fgets | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-86729@lists.php.net to get a copy of this message | ||
It seems to me that the main example for fgets() is misleading. This example, used as written, will
process all the code in the "while" once for each line of the file, and once again after
feof() becomes true after the fgets(). The "echo $buffer" statement gets executed even
when $buffer has not been returned.
Upon investigation I found that $buffer is indeed set to false when the fgets() attempts to read at
EOF. This would seem appropriate:
<?php
$handle = fopen("/tmp/inputfile.txt", "r");
while ($buffer = fgets($handle,4096)) {
echo $buffer;
}
fclose($handle);
?>
The original example could be coded as:
<?php
$handle = fopen("/tmp/inputfile.txt", "r");
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
if (!feof($handle)) {
echo $buffer;
}
}
fclose($handle);
?>
----
Manual Page -- http://www.php.net/manual/en/function.fgets.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+51125
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+51125&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+51125&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+51125&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+51125&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+51125&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+51125&report=yes
Search -- http://master.php.net/manage/user-notes.php