函数名称:fwrite()
适用版本:所有版本的 PHP
函数描述:fwrite() 函数用于向文件中写入数据。如果成功则返回写入的字节数,如果失败则返回 false。
语法:fwrite(file, string, length)
参数:
- file:必需,要写入的文件的文件指针。
- string:必需,要写入文件的字符串。
- length:可选,要写入的最大字节数,默认为文件的长度。
返回值:成功时返回写入的字节数,失败时返回 false。
示例1:向文件中写入字符串
$file = fopen("test.txt", "w");
if ($file) {
$string = "Hello, world!";
$bytes_written = fwrite($file, $string);
if ($bytes_written !== false) {
echo "成功写入了 " . $bytes_written . " 字节的数据。";
} else {
echo "写入文件失败。";
}
fclose($file);
} else {
echo "打开文件失败。";
}
示例2:写入指定字节数的数据
$file = fopen("test.txt", "w");
if ($file) {
$string = "This is a long text.";
$length = 10;
$bytes_written = fwrite($file, $string, $length);
if ($bytes_written !== false) {
echo "成功写入了 " . $bytes_written . " 字节的数据。";
} else {
echo "写入文件失败。";
}
fclose($file);
} else {
echo "打开文件失败。";
}
注意事项:
- 在使用 fwrite() 函数前,必须先使用 fopen() 函数打开文件,并确保文件指针有效。
- 在写入数据之后,应使用 fclose() 函数关闭文件指针,释放资源。
- 如果文件不存在,则 fwrite() 函数会创建一个新文件。
- 如果文件已存在且打开模式为 "w",则会清空文件内容并写入新数据。
- 可以使用 fwrite() 函数写入二进制数据或文本数据。
- 如果写入的字节数小于指定的长度,则可能是写入失败或到达了文件末尾。