fwrite 用于向已打開的文件寫入數(shù)據(jù),語法為 fwrite($handle, $string, $length = null),其中 $handle 是文件指針,$string 是要寫入的數(shù)據(jù),$length 是要寫入的字節(jié)數(shù)(可選)。fwrite 成功寫入時(shí)返回寫入的字節(jié)數(shù),失敗時(shí)返回 false。
fwrite 函數(shù)在 PHP 中的用法
什么是 fwrite?
fwrite 是 PHP 中一個(gè)內(nèi)置函數(shù),用于向已打開的文件寫入數(shù)據(jù)。
語法:
<code class="php">int fwrite(resource $handle, string $string, int $length = NULL)</code>
登錄后復(fù)制
參數(shù):
$handle:已打開的文件指針,由 fopen() 函數(shù)返回。
$string:要寫入文件的數(shù)據(jù)(字符串)。
$length:要寫入的字節(jié)數(shù)(可選)。默認(rèn)為 strlen($string)。
返回值:
fwrite 成功寫入數(shù)據(jù)時(shí)返回寫入的字節(jié)數(shù),寫入失敗時(shí)返回 FALSE。
用法:
打開文件后,可以使用 fwrite 函數(shù)向文件中寫入數(shù)據(jù):
<code class="php">$handle = fopen("myfile.txt", "w");
fwrite($handle, "Hello, world!");
fclose($handle);</code>
登錄后復(fù)制
上面的代碼將字符串 “Hello, world!” 寫入名為 “myfile.txt” 的文件中。
注意:
如果文件成功打開,fwrite 才會(huì)開始寫入。
如果文件以只讀模式打開,fwrite 將失敗。
如果寫入的數(shù)據(jù)超出了給定的文件大小限制,fwrite 將截?cái)鄶?shù)據(jù)。
成功寫入后,需要使用 fclose() 函數(shù)關(guān)閉文件。






