打开文件
fopen()函数用于在php中打开文件。
例子:
<?php
$file=fopen("welcome.txt","r");
?>
第一个参数含有要打开的文件的名称,第二个参数规定了使用哪种模式来打开文件
如果fopen()函数无法打开指定文件,则返回0(false)。
如果fopen()函数无法打开指定文件,则让他生成一段消息如:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
关闭文件
fclose()函数用于关闭打开的文件:
<?php
$file = fopen("test.txt","r"); //执行一些代码
fclose($file);
?>
检测文件末尾(EOF)
feof()函数检测是否已到达文件末尾(EOF).
在W(只写)、a(追加)、和x(只写)模式下,无法读取打开文件
if (feof($file)) echo "文件结尾";
逐行读取文件
fegets()函数用于从文件中逐行读取文件。
<?php
$file = fopen("welcome.txt", "r") or exit("无法打开文件!"); // 读取文件每一行,直到文件结尾
while(!feof($file)){
echo fgets($file). "<br>";
}
fclose($file);
?>
逐字符读取文件
fgetc()函数用于从文件中逐字符地读取文件。
<?php
$file=fopen("welcome.txt","r") or exit("无法打开文件!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>