fread 读取文件(可安全用于二进制文件)

发表日期:2021-07-01 08:55:43 | 来源: | | 浏览(813) 分类:文件系统函数

fread

(PHP 4, PHP 5, PHP 7, PHP 8)

fread读取文件(可安全用于二进制文件)

说明

fread(resource $handle, int $length): string

fread() 从文件指针   handle 读取最多   length 个字节。     该函数在遇上以下几种情况时停止读取文件:

  •  读取了 length 个字节    

  •  到达了文件末尾(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.    


参数


  • handle

  • 文件系统指针,是典型地由fopen() 创建的 resource(资源)。

  • length

  • 最多读取 length 个字节。


返回值

返回所读取的字符串, 或者在失败时返回 false

范例


示例 #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);
?>



示例 #2 Binary fread() example

警告

在区分二进制文件和文本文件的系统上(如    Windows)打开文件时,fopen() 函数的 mode 参数要加上 'b'。

<?php 
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>



示例 #3 Remote fread() examples

警告

当从任何不是普通本地文件读取时,例如在读取从远程文件或popen() 以及 fsockopen()返回的流时,读取会在一个包可用之后停止。这意味着应该如下例所示将数据收集起来合并成大块。

<?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);
?>


注释

注意:

如果只是想将一个文件的内容读入到一个字符串中,用file_get_contents(),它的性能比上面的代码好得多。


注意:

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() - 打开一个网络连接或者一个Unix套接字连接

  • popen() - 打开进程文件指针

  • fgets() - 从文件指针中读取一行

  • fgetss() - 从文件指针中读取一行并过滤掉 HTML 标记

  • fscanf() - 从文件中格式化输入

  • file() - 把整个文件读入一个数组中

  • fpassthru() - 输出文件指针处的所有剩余数据

  • ftell() - 返回文件指针读/写的位置

  • rewind() - 倒回文件指针的位置


集速网 copyRight © 2015-2022 宁ICP备15000399号-1 宁公网安备 64010402001209号
与其临渊羡鱼,不如退而结网
欢迎转载、分享、引用、推荐、收藏。