PHP fputs 函数
最后修改于 2025 年 4 月 3 日
PHP 的 fputs
函数将数据写入文件。它与 fwrite
相同,并提供低级文件写入功能。
基本定义
fputs
函数将字符串写入文件指针。它接受三个参数:文件句柄、要写入的字符串和可选长度。
语法:fputs(resource $handle, string $string, int $length = ?): int
。它返回写入的字节数,失败时返回 false。
基本的 fputs 示例
这展示了 fputs
写入文件的最简单用法。
basic_fputs.php
<?php declare(strict_types=1); $file = fopen("output.txt", "w"); if ($file) { $bytes = fputs($file, "Hello, World!"); fclose($file); echo "Wrote $bytes bytes to file."; }
这会将 "Hello, World!" 写入 output.txt。始终检查 fopen 是否成功,并记住完成后使用 fclose 关闭文件。
追加到文件
使用 "a" 模式将内容附加到现有文件。
append_fputs.php
<?php declare(strict_types=1); $file = fopen("log.txt", "a"); if ($file) { $message = date('Y-m-d H:i:s') . " - User logged in\n"; fputs($file, $message); fclose($file); }
这会将带时间戳的消息附加到 log.txt。 "a" 模式会在文件不存在时创建它,并保留现有内容。
写入二进制数据
使用 "b" 模式标志时,fputs
可以写入二进制数据。
binary_fputs.php
<?php declare(strict_types=1); $file = fopen("data.bin", "wb"); if ($file) { $binaryData = pack('C*', 0x48, 0x65, 0x6C, 0x6C, 0x6F); $bytes = fputs($file, $binaryData); fclose($file); echo "Wrote $bytes bytes of binary data."; }
这会将二进制数据("Hello" 的 ASCII 码)写入文件。 "b" 模式可确保跨平台正确处理二进制数据。
带长度限制的写入
可选的长度参数限制了写入的字节数。
length_fputs.php
<?php declare(strict_types=1); $file = fopen("partial.txt", "w"); if ($file) { $text = "This is a long string that will be truncated"; $bytes = fputs($file, $text, 10); fclose($file); echo "Wrote first $bytes characters: " . substr($text, 0, 10); }
这只写入字符串的前 10 个字节。当您需要写入固定大小的数据块时,长度参数非常有用。
错误处理
适当的错误处理可确保文件写入的健壮性。
error_fputs.php
<?php declare(strict_types=1); $file = @fopen("readonly.txt", "w"); if ($file === false) { die("Failed to open file"); } $result = fputs($file, "Attempt to write"); if ($result === false) { echo "Failed to write to file"; } else { echo "Successfully wrote $result bytes"; } fclose($file);
这展示了对文件打开和写入的适当错误检查。@ 抑制警告,允许自定义错误处理。
最佳实践
- 检查返回值:始终验证 fputs 的返回值。
- 适当的模式:使用正确的文件打开模式。
- 资源清理:始终使用 fclose 关闭文件。
- 错误处理:实现全面的错误检查。
- 二进制安全:二进制数据使用 "b" 模式。
来源
本教程通过实际示例介绍了 PHP fputs
函数,展示了其在不同场景下的用法。
作者
列出 所有 PHP 文件系统函数。