PHP | fputs()函数

PHP中的fputs()函数是一个内置函数,用于写入打开的文件。 fputs()函数在文件末尾或达到作为参数传递的指定长度时停止,以先到者为准。 必须写入的文件、字符串和长度作为参数发送给fputs()函数,它在成功时返回写入的字节数,在失败时返回FALSE。 fputs()函数是fwrite()函数的别名。

null

语法:

fputs(file, string, length)

使用的参数: PHP中的fputs()函数接受三个参数。

  1. 文件:它是指定文件的必需参数。
  2. 字符串:它是一个强制参数,指定要写入的字符串。
  3. 长度:它是一个可选参数,指定要写入的最大字节数。

返回值: 它返回成功时写入的字节数,或失败时返回False。

例外情况

  1. 由于fputs()是二进制安全的,因此可以使用此函数写入二进制数据,如图像和字符数据。
  2. 不带length参数的fputs()函数将所有数据写到末尾,但不包括遇到的第0个字节。

例如:

Input : $myfile = fopen("gfg.txt", "w");
        echo fputs($myfile, "Geeksforgeeks is a portal of geeks!");
        fclose($myfile);
Output : 35

Input : $myfile = fopen("gfg.txt", "w");
        echo fputs($myfile, "Geeksforgeeks is a portal of geeks!", 13);
        fclose($myfile);
        fopen("gfg.txt", "r");
        echo fread($myfile, filesize("gfg.txt"));
        fclose($myfile);
Output : Geeksforgeeks

下面的程序演示了fputs()函数:

方案1

<?php
// Opening a file
$myfile = fopen ( "gfg.txt" , "w" );
// writing content to a file using fputs
echo fputs ( $myfile , "Geeksforgeeks is a portal of geeks!" );
// closing the file
fclose( $myfile );
?>


输出:

35

方案2

<?php
// Opening a file
$myfile = fopen ( "gfg.txt" , "w" );
// writing content to a file with a specified string length using fputs
echo fputs ( $myfile , "Geeksforgeeks is a portal of geeks!" , 13);
// closing the file
fclose( $myfile );
//opening the same file to read its contents
fopen ( "gfg.txt" , "r" );
echo fread ( $myfile , filesize ( "gfg.txt" ));
// closing the file
fclose( $myfile );
?>


输出:

Geeksforgeeks

参考: http://php.net/manual/en/function.fputs.php

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享