首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

fread

(PHP 4, PHP 5, PHP 7)

fread - 读取二进制安全文件

描述

代码语言:javascript
复制
string fread ( resource $handle , int $length )

fread()length从指向的文件指针读取字节handle。只要符合以下条件之一,读数就会停止:

  • length 字节已被读取
  • EOF(文件结束)已到达
  • 一个数据包变得可用或发生套接字超时(针对网络流)
  • 如果流被读取缓冲,并且它不表示一个普通文件,则最多只能读取一个等于块大小(通常为8192)的字节数; 取决于先前缓冲的数据,返回的数据的大小可能大于块大小。

参数

handle

通常使用fopen()创建的文件系统指针资源。

length

最多length读取的字节数。

返回值

返回读取字符串或FALSE失败。

例子

Example #1 A simple fread() example

代码语言:javascript
复制
<?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

在区分二进制文件和文本文件的系统上(例如Windows),必须使用fopen()模式参数中包含的'b'打开文件。

代码语言:javascript
复制
<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example #3 Remote fread() examples

警告

当读取任何非常规本地文件(例如读取远程文件或从popen()和fsockopen()返回的流)时,数据包可用后读取将停止。这意味着您应该按照下面的示例所示以块的形式收集数据。

代码语言:javascript
复制
<?php
// For PHP 5 and up
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>
代码语言:javascript
复制
<?php
$handle = fopen("http://www.example.com/", "rb");
if (FALSE === $handle) {
    exit("Failed to open stream to URL");
}

$contents = '';

while (!feof($handle)) {
    $contents .= fread($handle, 8192);
}
fclose($handle);
?>

注意

注意:如果您只想将文件内容转换为字符串,请使用file_get_contents(),因为它具有比上述代码更好的性能。

注意:请注意,fread()从文件指针的当前位置读取。使用ftell()来查找指针的当前位置,并使用rewind()来倒回指针位置。

  • fscanf() - 根据格式解析文件的输入
  • file() - 将整个文件读入一个数组
  • fpassthru() - 输出文件指针上的所有剩余数据
  • ftell() - Returns the current position of the file read/write pointer
  • 倒回() - 倒回文件指针的位置
  • unpack() - 从二进制字符串解压数据

← fputs

fscanf →

扫码关注腾讯云开发者

领取腾讯云代金券