fwrite

(PHP 4, PHP 5, PHP 7)

fwriteд���ļ����ɰ�ȫ���ڶ������ļ���

˵��

fwrite ( resource $handle , string $string [, int $length ] ) : int

fwrite() �� string ������д�� �ļ�ָ�� handle ����

����

handle

�ļ�ϵͳָ�룬�ǵ��͵��� fopen() ������ resource(��Դ)��

string

The string that is to be written.

length

���ָ���� length����д���� length ���ֽڻ���д���� string �Ժ�д��ͻ�ֹͣ���Ӻ����������������

ע����������� length �������� magic_quotes_runtime ����ѡ������ԣ��� string �е�б�߽����ᱻ��ȥ��

����ֵ

fwrite() ����д����ַ��������ִ���ʱ�򷵻� FALSE ��

ע��

Note:

Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

<?php
function fwrite_stream($fp$string) {
    for (
$written 0$written strlen($string); $written += $fwrite) {
        
$fwrite fwrite($fpsubstr($string$written));
        if (
$fwrite === false) {
            return 
$written;
        }
    }
    return 
$written;
}
?>

Note:

�����ֶ������ļ����ı��ļ���ϵͳ�ϣ��� Windows�� ���ļ�ʱ��fopen() ������ mode ����Ҫ���� 'b'��

Note:

If handle was fopen()ed in append mode, fwrite()s are atomic (unless the size of string exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.

Note:

If writing twice to the file pointer, then the data will be appended to the end of the file content:

<?php
$fp 
fopen('data.txt''w');
fwrite($fp'1');
fwrite($fp'23');
fclose($fp);

// the content of 'data.txt' is now 123 and not 23!
?>

����

Example #1 һ���򵥵� fwrite() ����

<?php
$filename 
'test.txt';
$somecontent "�����Щ���ֵ��ļ�\n";

// ��������Ҫȷ���ļ����ڲ��ҿ�д��
if (is_writable($filename)) {

    
// �������������ǽ�ʹ�����ģʽ��$filename��
    // ��ˣ��ļ�ָ�뽫�����ļ���ĩβ��
    // �Ǿ��ǵ�����ʹ��fwrite()��ʱ��$somecontent��Ҫд��ĵط���
    
if (!$handle fopen($filename'a')) {
         echo 
"���ܴ��ļ� $filename";
         exit;
    }

    
// ��$somecontentд�뵽���Ǵ򿪵��ļ��С�
    
if (fwrite($handle$somecontent) === FALSE) {
        echo 
"����д�뵽�ļ� $filename";
        exit;
    }

    echo 
"�ɹ��ؽ� $somecontent д�뵽�ļ�$filename";

    
fclose($handle);

} else {
    echo 
"�ļ� $filename ����д";
}
?>

�μ�

  • fread() - ��ȡ�ļ����ɰ�ȫ���ڶ������ļ���
  • fopen() - ���ļ����� URL
  • fsockopen() - ��һ���������ӻ���һ��Unix�׽�������
  • popen() - �򿪽����ļ�ָ��
  • file_get_contents() - �������ļ�����һ���ַ���