在 PHP 中,fputs 函数用于向打开的文件写入数据。它与 fwrite 函数类似,都是用来写入文件的。fputs 函数的语法如下:
fputs(resource $handle, string $string, int $length = null): int|false 参数说明:
$handle:表示文件指针,使用 fopen 函数打开文件后返回的资源。$string:要写入文件的字符串。$length:可选参数,表示要写入的最大字节数。如果省略该参数,则会将整个字符串写入文件。fputs 函数会返回写入文件的字节数,如果写入失败,则返回 false。
示例:
$handle = fopen("file.txt", "w"); if ($handle) { $bytes_written = fputs($handle, "Hello, World!"); if ($bytes_written !== false) { echo "Data written successfully: $bytes_written bytes."; } else { echo "Failed to write data to file."; } fclose($handle); } else { echo "Failed to open file for writing."; } 在使用 fputs 函数写入文件时,需要确保文件已经以写入模式打开,并在操作完成后关闭文件资源。