fwrite
fwrite
(PHP 4, PHP 5, PHP 7)
fwrite - 二进制安全文件写入
描述
int fwrite ( resource $handle , string $string [, int $length ] )
fwrite()
将内容写入string
指向的文件流handle
。
参数
handle
通常使用fopen()创建的文件系统指针资源。
string
要写入的字符串。
length
如果length
给出了自变量,写入length
字节后或写入结束后停止写入string
,以先到者为准。
请注意,如果length
给出参数,那么magic_quotes_runtime配置选项将被忽略,并且不会从任何斜杠中删除string
。
返回值
fwrite()
返回写入的字节数,或者返回FALSE
错误。
注意
注意:在写入整个字符串之前,写入网络流可能会结束。可以检查fwrite()的返回值:<?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()模式参数中包含的'b'打开文件。
注意
:如果handle
以附加模式执行fopen(),则fwrite()
s是原子的(除非string
文件系统的块大小超过文件系统的块大小,在某些平台上,只要文件位于本地文件系统中)。也就是说,在调用fwrite()
之前,不需要flock()资源。所有的数据将被不间断地写入。
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 A simple fwrite() example
<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle
} else {
echo "The file $filename is not writable";
}
?>