程式在寫時, 何時要用 fgets? 何時要用 fread? 主要的差異在哪邊? 以下就用簡單的範例來說明~
先建立一個檔案: /tmp/readfile.txt, 內容如下:
abcdefg
123456789
寫兩隻簡單的小程式:
fgets 版
<?php
$handle = fopen('/tmp/readfile.txt', "r");
$contents = '';
if ($handle) {
while (!feof($handle)) {
$contents = fgets($handle, 10);
echo $contents;
exit;
}
fclose($handle);
}
?>
執行得到的內容:
abcdefg
fread 版
<?php
$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. 🙂