如果 fopen() 不能打开指定的文件,下面的例子会生成一段消息:
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>
关闭文件
fclose() 函数用于关闭打开的文件。
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
检测 End-of-file
feof() 函数检测是否已达到文件的末端 (EOF)。
在循环遍历未知长度的数据时,feof() 函数很有用。
注释:在 w 、a 以及 x 模式,您无法读取打开的文件!
if (feof($file)) echo "End of file";
逐行读取文件
fgets() 函数用于从文件中逐行读取文件。
注释:在调用该函数之后,文件指针会移动到下一行。
例子
下面的例子逐行读取文件,直到文件末端为止:
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
逐字符读取文件
fgetc() 函数用于从文件逐字符地读取文件。
注释:在调用该函数之后,文件指针会移动到下一个字符。
例子
下面的例子逐字符地读取文件,直到文件末端为止:
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
Warning: move_uploaded_file(/dest/inat/ion.ext) [function.move-uploaded-file]: failed to open stream: No such file or directory in /upload/handler.php on line X
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/temp/file/name' to '/dest/inat/ion.ext' in /upload/handler.php on line X
Warning: move_uploaded_file(upload/12.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied inupload_file.php on line24
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/saetmp/928/xququer/1359821561_2429732845/phppSXyZ6' to 'upload/12.jpg' inupload_file.php on line24