fwrite 写入文件(可安全用于二进制文件)

发表日期:2021-07-01 08:55:43 | 来源: | | 浏览(838) 分类:文件系统函数

fwrite

(PHP 4, PHP 5, PHP 7, PHP 8)

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

注释

注意:

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($fp, substr($string, $written));
        if ($fwrite === false) {
            return $written;
        }
    }
    return $written;
}
?>



注意:

在区分二进制文件和文本文件的系统上(如 Windows)    打开文件时,fopen() 函数的 mode 参数要加上 'b'。


注意:

If handle was fopen()ed in    append mode, fwrite()s are atomic (unless the size ofstring 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 callingfwrite(); all of the data will be written without    interruption.


注意:

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!?>



范例


示例 #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 不可写";
}
?>


参见



集速网 copyRight © 2015-2022 宁ICP备15000399号-1 宁公网安备 64010402001209号
与其临渊羡鱼,不如退而结网
欢迎转载、分享、引用、推荐、收藏。