(PHP 4, PHP 5)
fread — 讀取文件(可安全用于二進制文件)
說明
string fread ( resource$handle
, int $length
)
fread() 從文件指針
handle
讀取最多
length
個字節(jié)。
該函數(shù)在遇上以下幾種情況時停止讀取文件:
讀取了 length
個字節(jié)
到達了文件末尾(EOF)
a packet becomes available or the
socket timeout occurs (for network streams)
if the stream is read buffered and it does not represent a plain file, at
most one read of up to a number of bytes equal to the chunk size (usually
8192) is made; depending on the previously buffered data, the size of the
returned data may be larger than the chunk size.
參數(shù)
handle
文件系統(tǒng)指針,是典型地由 fopen() 創(chuàng)建的 resource(資源)。
length
最多讀取 length
個字節(jié)。
返回值
返回所讀取的字符串, 或者在失敗時返回 FALSE
。
范例
Example #1 一個簡單的 fread() 例子
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
Example #2 Binary fread() example
Warning在區(qū)分二進制文件和文本文件的系統(tǒng)上(如 Windows)打開文件時,fopen() 函數(shù)的 mode 參數(shù)要加上 'b'。
<?php
$filename = "c:\files\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
Example #3 Remote fread() examples
Warning當(dāng)從任何不是普通本地文件讀取時,例如在讀取從遠程文件或 popen() 以及 fsockopen() 返回的流時,讀取會在一個包可用之后停止。這意味著應(yīng)該如下例所示將數(shù)據(jù)收集起來合并成大塊。
<?php
// 對 PHP 5 及更高版本
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle = fopen("http://www.example.com/", "rb");
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
?>
注釋
Note:
如果只是想將一個文件的內(nèi)容讀入到一個字符串中,用 file_get_contents(),它的性能比上面的代碼好得多。
Note:
Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position.
參見
fwrite() - 寫入文件(可安全用于二進制文件) fopen() - 打開文件或者 URL fsockopen() - 打開一個網(wǎng)絡(luò)連接或者一個Unix套接字連接 popen() - 打開進程文件指針 fgets() - 從文件指針中讀取一行 fgetss() - 從文件指針中讀取一行并過濾掉 HTML 標(biāo)記 fscanf() - 從文件中格式化輸入 file() - 把整個文件讀入一個數(shù)組中 fpassthru() - 輸出文件指針處的所有剩余數(shù)據(jù) ftell() - 返回文件指針讀/寫的位置 rewind() - 倒回文件指針的位置