PHP如何使用fclose()函数?用法示例解读

2021年4月2日11:19:16 发表评论 708 次浏览

PHP中的fclose()函数是一个内置函数, 用于关闭由打开的文件指针指向的文件。 fclose()函数在成功时返回true, 在失败时返回false。它将文件作为必须关闭的参数, 然后关闭该文件。

语法如下:

bool fclose( $file )

参数:PHP中的fclose()函数仅接受一个参数, 即$ file。此参数指定必须关闭的文件。

返回值:成功返回true, 失败返回false。

错误与异常:

如果已通过fwrite()函数写入文件, 则必须首先使用fclose()函数将其关闭, 并且你必须读取文件的内容。

PHP中的fclose()函数不适用于远程文件, 仅适用于服务器文件系统可访问的文件。

例子:

Input : $check = fopen("gfg.txt", "r");
        fclose($check);
Output : true

Input: $check = fopen("singleline.txt", "r");
       $seq = fgets($check);
       while(! feof($check))
       {
         echo $seq ;
         $seq = fgets($check);
       }
       fclose($check);
Output:true

下面的程序说明了fclose()函数:

程序1:

<?php
  
// opening a file using fopen() function
$check = fopen ( "gfg.txt" , "r" );
  
// closing a file using fclose() function
fclose( $check );
  
?>

输出如下:

true

程序2:在以下程序中, 文件名为singleline.txt仅包含一行"此文件仅包含一行"。

<?php
  
// a file is opened using fopen() function
$check = fopen ( "singleline.txt" , "r" );
$seq = fgets ( $check );
  
// Outputs a line of the file until
// the end-of-file is reached
while (! feof ( $check ))
{
   echo $seq ;
   $seq = fgets ( $check );
}
  
// the file is closed using fclose() function
fclose( $check );
  
?>

输出如下:

This file consists of only a single line.

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


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: