程序在写时, 何时要用 fgets? 何时要用 fread? 主要的差异在哪边? 以下就用简单的范例来说明~
先创建一个文件: /tmp/readfile.txt, 内容如下:
abcdefg
123456789
写两只简单的小程序:
fgets 版
$handle = fopen('/tmp/readfile.txt', "r");
$contents = '';
if ($handle) {
while (!feof($handle)) {
$contents = fgets($handle, 10);
echo $contents;
exit;
}
fclose($handle);
}
?>
运行得到的内容:
abcdefg
fread 版
$handle = fopen('/tmp/readfile.txt', "r");
$contents = '';
if ($handle) {
while (!feof($handle)) {
$contents .= fread($handle, 10);
echo $contents;
exit;
}
fclose($handle);
}
?>
运行得到的内容:
abcdefg
12
fgets 和 fread 主要的差异
fgets 是 一次读一行 (Gets a line from file pointer.)
fread 会把整个文件都读出来, 然后再去看要抓多少 bytes.
所以 fgets 读到的是第一行到结束(后面参数不加, 就会读到此行结束), fread 读到的是 "abcdefg\n12" (\n 算一个 bytes), 就是看到的结果啰~
使用的时机就自行看情况啰~ 若读的文件太大, 建议使用 fgets.