fopen() 的第一个参数包含被打开的文件名,第二个参数规定打开文件的模式。如果 fopen() 函数未能打开指定的文件,下面的例子会生成一段消息:
<?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("webdictionary.txt")); fclose($myfile); ?>
fread() 函数读取打开的文件。
fread() 的第一个参数包含待读取文件的文件名,第二个参数规定待读取的最大字节数。
如下 PHP 代码把 "webdictionary.txt" 文件读至结尾:
fread($myfile,filesize("webdictionary.txt"));
fclose() 函数用于关闭打开的文件。
注释:用完文件后把它们全部关闭是一个良好的编程习惯。您并不想打开的文件占用您的服务器资源。
fclose() 需要待关闭文件的名称(或者存有文件名的变量):
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
fgets() 函数用于从文件读取单行。
下例输出 "webdictionary.txt" 文件的首行:
<?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fgets($myfile); fclose($myfile); ?>
评论