PHP中的fgets()函数是一个内置函数,用于从打开的文件返回一行。
它用于从文件指针返回一行,并且它以指定的长度停止返回,即在文件末尾(EOF)或在新行中,以先到者为准。
要读取的文件和要读取的字节数作为参数发送到fgets()函数,并且它从用户指向的文件中返回长度为-1个字节的字符串。
失败时返回False。
用法:fgets(file, length)
Parameters Used:
The fgets() function in PHP accepts two parameters.
file : It specifies the file from which characters have
to be extracted.
length : It specifies the number of bytes to be
read by the fgets() function. The default value
is 1024 bytes.
返回值:它从用户指向的文件中返回长度为-1个字节的字符串,否则返回False。
错误与异常
该功能并未针对大型文件进行优化,因为它一次只能读取一行,并且可能需要大量时间才能完全读取一个长文件。
如果多次使用fgets()函数,则必须清除缓冲区。
fgets()函数返回布尔值False,但是很多时候它返回一个非布尔值,该值的值为False。
假设有一个名为“gfg.txt”的文件,该文件包括:
This is the first line.
This is the second line.
This is the third line.
程序1
// file is opened using fopen() function
$my_file = fopen("gfg.txt", "rw");
// Prints a single line from the opened file pointer
echo fgets($my_file);
// file is closed using fclose() function
fclose($my_file);
?>
输出:
This is the first line.
程序2
//file is opened using fopen() function
$my_file = fopen("gfg.txt", "rw");
// prints a single line at a time until end of file is reached
while (! feof ($my_file))
{
echo fgets($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.