API16

API16:JStream/write

From Joomla! Documentation

Revision as of 22:48, 22 March 2010 by Doxiki (talk | contribs) (New page: ===Description=== File write Note: Whilst this function accepts a reference, the underlying fwrite will do a copy! This will roughly double the memory allocation for any write you do. Spe...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Description

File write Note: Whilst this function accepts a reference, the underlying fwrite will do a copy! This will roughly double the memory allocation for any write you do. Specifying chunked will get around this by only writing in specific chunk sizes. This defaults to 8192 which is a sane number to use most of the time (change the default with JStream::set('chunksize', newsize);) Note: This doesn't support gzip/bzip2 writing like reading does

[Edit Descripton]

Template:Description:JStream/write

Syntax

write(&$string, $length=0, $chunk=0)
Parameter Name Default Value Description
Reference to the string to write
$length 0 Length of the string to write
$chunk 0 Size of chunks to write in

Defined in

libraries/joomla/filesystem/stream.php

Importing

jimport( 'joomla.filesystem.stream' );

Source Body

function write(&$string, $length=0, $chunk=0)
{
        if(!$this->_fh)
        {
                $this->setError(JText::_('File not open'));
                return false;
        }
        // if the length isn't set, set it to the length of the string
        if(!$length) $length = strlen($string);
        // if the chunk isn't set, set it to the default
        if(!$chunk) $chunk = $this->chunksize;
        $retval = true;
        // Capture PHP errors
        $php_errormsg = '';
        $track_errors = ini_get('track_errors');
        ini_set('track_errors', true);
        $remaining = $length;
        do {
                // if the amount remaining is greater than the chunk size, then use the chunk
                $amount = ($remaining > $chunk) ? $chunk : $remaining;
                $res = fwrite($this->_fh, $string, $amount);
                // returns false on error or the number of bytes written
                if($res === false)
                { // returned error
                        $this->setError($php_errormsg);
                        $retval = false;
                        $remaining = 0;
                }
                else if($res === 0)
                { // wrote nothing?
                        $remaining = 0;
                        $this->setError('Warning: No data written');
                } else
                { // wrote something
                        $remaining -= $res;
                }
        } while($remaining);

        // restore error tracking to what it was before
        ini_set('track_errors',$track_errors);
        // return the result
        return $retval;
}

[Edit See Also] Template:SeeAlso:JStream/write

Examples

<CodeExamplesForm />