php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #34860 fwrite returns 0 instead of false on some failures
Submitted: 2005-10-13 21:04 UTC Modified: 2005-10-14 14:50 UTC
From: aaron-php at oakadaptive dot com Assigned:
Status: Not a bug Package: Filesystem function related
PHP Version: 5.0.5 OS: Linux (Red Hat and SUSE)
Private report: No CVE-ID: None
 [2005-10-13 21:04 UTC] aaron-php at oakadaptive dot com
Description:
------------
When fwrite can't write its whole second argument, it
returns the number of bytes it did succeed in writing
instead of false.

This behavior is mentioned in the user comments for fwrite,
but I couldn't find it reported as a bug.  I consider it a
bug, because it makes testing for a failed fwrite harder;
it's necessary to compare the length of the string with
fwrite's return value.

If it is intended behavior, I think the documentation should
be clearer, explicitly saying that if fwrite does return an
int, it can be less than the string's length (and as little
as zero).

(fwrite does return false if, for instance, its first
argument is not a file handle.  It also triggers a warning.)

Reproduce code:
---------------
$Filename = 'deleteme';
if (touch($Filename)): // Make sure file exists.
  $FileHnd = fopen($Filename, 'r'); // Open read-only.
  if ($FileHnd):
    $ByteCount = fwrite($FileHnd, 'test'); // Try to write 4 bytes.
    if ($ByteCount === false):
      echo "fwrite() returned false\n";
    else:
      echo "fwrite() wrote $ByteCount byte(s)\n"; // Reports
        // that 0 bytes were written (tested on v.  5.0.5 and 4.3.4):
    endif;
    fclose($FileHnd);
    unlink($Filename); // Clean up.
  endif;
endif;

Expected result:
----------------
fwrite() returned false

Actual result:
--------------
fwrite() wrote 0 byte(s)

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-10-14 13:32 UTC] tony2001@php.net
The docs are clear about it:
"fwrite() returns the number of bytes written, or FALSE on error".

There were no error, but 0 bytes were written (because of the obvious reason).
 [2005-10-14 14:50 UTC] aaron-php at oakadaptive dot com
> The docs are clear about it:
>
>> "fwrite() returns the number of bytes written, or FALSE
>> on error".
>
> There were no error, but 0 bytes were written (because of
> the obvious reason).

I still think more explicit documentation would be an
improvement.  I made the incorrect but, in my opinion,
natural assumption that a failure to write what I requested
would be considered an error (and that the return value was
just for convenience).

-- 
Aaron
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Apr 20 03:01:28 2024 UTC