php fwrite 二进制安全,写入文件(可安全用于二进制文件) - PHP 7 中文文档

本文详细介绍了PHP的fwrite()函数,用于向文件写入数据。它接受文件指针、要写入的字符串和可选的长度参数。fwrite()是原子性的,意味着在可写文件上进行的多次写入操作会连续进行,不会被其他进程打断。文章还提供了一个简单的示例,展示了如何在PHP中使用fwrite()向文件追加内容。
摘要由CSDN通过智能技术生成

(PHP 4, PHP 5, PHP 7)

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

说明

fwrite

( resource $handle

, string $string

[, int $length

] ) : int

fwrite() 把 string 的内容写入

文件指针 handle 处。

参数

handle

文件系统指针,是典型地由

[fopen()](php7/function.fopen) 创建的 [resource](php7/language.types.resource)(资源)。

string

The string that is to be written.

length

如果指定了

length,当写入了

length 个字节或者写完了 string

以后,写入就会停止,视乎先碰到哪种情况。

注意如果给出了

length

参数,则 [magic_quotes_runtime](php7/info.configuration)

配置选项将被忽略,而

string 中的斜线将不会被抽去。

返回值

fwrite() 返回写入的字符数,出现错误时则返回 FALSE 。

注释

Note:

Writing to a network stream may end before the whole string is written.

Return value of fwrite() may be checked:

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;

}

?>

Note:

在区分二进制文件和文本文件的系统上(如 Windows)

打开文件时,[fopen()](php7/function.fopen) 函数的 mode 参数要加上 'b'。

Note:

If handle was [fopen()](php7/function.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()](php7/function.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:

$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() 例子

$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()](php7/function.fread) – 读取文件(可安全用于二进制文件)

[fopen()](php7/function.fopen) – 打开文件或者 URL

[fsockopen()](php7/function.fsockopen) – 打开一个网络连接或者一个Unix套接字连接

[popen()](php7/function.popen) – 打开进程文件指针

[file_get_contents()](php7/function.file-get-contents) – 将整个文件读入一个字符串

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值