zoukankan      html  css  js  c++  java
  • PHP读取文件函数fread,fgets,fgetc,file_get_contents和file函数的使用总结

      fread()、fgets()、fgetc()、file_get_contents() 与 file() 函数用于从文件中读取内容。

      1.fread()

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

      语法:string fread(int handle,int length)

      fread() 从文件指针 handle 读取最多 length 个字节。当遇到下列任何一种情况时,会停止读取文件 

      1.在读取完最多 length 个字节数时

       2.达到文件末尾的时候(EOF)

        3.(对于网络流)当一个包可用时

        4.(在打开用户空间流之后)已读取了 8192 个字节时.                       例如:从文件test.txt中读取10个字节。

    <?php
        $filename = "test.txt";
        $fh = fopen($filename, "r");
        echo fread($fh, "10");
        fclose($fh);
    ?>
    

      2.fegts()

      fgets() 函数用于从文件中读取 一行 数据,并将文件指针指向下一行。提示:如果想在读取的时候去掉文件中的 HTML 标记,请使用 fgetss() 函数。

      语法:string fgets( int handle [,int length] )

      fgets() 从 handle 指向的文件中读取一行并返回长度最多为 length-1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length-1 字节后停止。如果没有指定 length ,则默认为 1K ,或者说 1024 字节。

    <?php
        $fh = @fopen("test.txt","r") or die("打开 test.txt 文件出错!");
        // if条件避免无效指针
        if($fh){
            while(!feof($fh)) {
                echo fgets($fh), '<br />';
            }
        }
        fclose($fh);
    ?>
    

      3.fgetc()

      fgetc()函数用于逐字读取文件数据,直到文件结束。

      语法:string fgetc( resource handle )

      

    <?php
        $fh = @fopen("test.txt","r") or die("打开 test.txt 文件出错!");
        if($fh){
            while(!feof($fh)) {
                echo fgetc($fh);
            }
        }
        fclose($fh);
    ?>
    

      4.file_get_contents()

      file_get_contents() 函数用于把 整个文件 读入一个字符串,成功返回一个字符串,失败则返回 FALSE。

       语法:string file_get_contents( string filename [, int offset [, int maxlen] ] )

      filename:要读取的文件名称

      offset:可选,指定读取位置,默认从文件开始位置

      maxlen:可选,指定读取文件的长度,单位字节

    <?php
        // 读取时同事将换行符转换成 <br />
        echo nl2br(file_get_contents('test.txt'));
    ?>
    

      5.file()

      file()函数用于把整个文件读入一个数组中,数组中的每个单元都是文件中相应的一行,包括换行符在内。成功返回一个数组,失败则返回 FALSE。

      语法:array file( string filename )

     

    <?php
        $lines = file('test.txt');
        // 在数组中循环并加上行号
        foreach ($lines as $line_num => $line) {
            echo "Line #{$line_num} : ",$line,'<br />';
        }
    ?>
    

      test.txt文件内容:

          你好!

          这是第二行文字。

      输出:

          line #0:你好!

          line #1:这是第二行文字。

     

  • 相关阅读:
    hosts 本机DNS域名解析
    五步搞定Android开发环境部署——非常详细的Android开发环境搭建教程
    OracleBulkCopy
    第三方登录(QQ登录)开发流程详解
    Asp.net MVC中Html.Partial, RenderPartial, Action,RenderAction 区别和用法
    MVC Return View() 和 Return PartialView()的区别
    如何选择Html.RenderPartial和Html.RenderAction
    C# Dictionary和Dynamic类型
    css01入门小例子
    html03表单
  • 原文地址:https://www.cnblogs.com/coderchuanyu/p/4237483.html
Copyright © 2011-2022 走看看