PHP如何使用fgetc()函数?用法实例

2021年3月30日11:31:40 发表评论 641 次浏览

PHP中的fgetc()函数是一个内置函数, 用于从打开的文件中返回单个字符。它用于从给定的文件指针获取字符。

要检查的文件用作fgetc()函数的参数, 它从文件中返回一个包含单个字符的字符串作为参数。

语法如下:

fgetc($file)

参数:PHP中的fgetc()函数仅接受一个参数$文件。它指定需要从中提取字符的文件。

返回值:它从文件中返回一个包含单个字符的字符串作为参数。

错误与异常:

  1. 该功能未针对大型文件进行优化, 因为它一次只能读取一个字符, 并且可能需要大量时间才能完全读取一个长文件。
  2. 如果多次使用fgetc()函数, 则必须清除缓冲区。
  3. fgetc()函数返回布尔False, 但是很多时候它返回一个非布尔值, 该值的值为False。

下面的程序说明了fgetc()函数。

程序1:在以下程序中, 文件名为gfg.txt包含以下文本。

这是第一行。这是第二行。这是第三行。

<?php
  
// file is opened using fopen() function
$my_file = fopen ( "gfg.txt" , "rw" );
  
// Prints a single character from the
// opened file pointer
echo fgetc ( $my_file );
  
// file is closed using fclose() function
fclose( $my_file );
  
?>

输出如下:

T

程序2:在以下程序中, 文件名为gfg.txt包含以下文本。

这是第一行。这是第二行。这是第三行。

<?php
  
// file is opened using fopen() function
$my_file = fopen ( "gfg.txt" , "rw" );
  
// prints single character at a time
// until end of file is reached
while (! feof ( $my_file ))
   {
   echo fgetc ( $my_file );
   }
  
// file is closed using fclose() function
fclose( $my_file );
?>

输出如下:

This is the first line.
This is the second line.
This is the third line.

参考:

http://php.net/manual/en/function.fgetc.php


木子山

发表评论

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