1.打开文件(fopen)
语法:resource $fp=fopen(文件地址,模式),返回的是文件指针(file pointer)
模式 | 含义 |
r | 只读 |
w | 写(清空重写) |
a | 追加 |
$fp = fopen(‘./aa.txt‘, "r"); //只读 $fp = fopen(‘./aa.txt‘, "w"); //写(清空重写) $fp = fopen(‘./aa.txt‘, "a"); //追加
2.读文件(fread ,file_get_contents)
语法:string fread ( $fp , 文件大小 )
file_get_contents 将整个文件读入一个字符串
语法:string file_get_contents ( string $filename)
<?php $filename = ‘./aa.txt‘; echo "<br><br>******第一种读取方法********<br>"; $fp = fopen($filename, "r"); $con = fread($fp, filesize($filename)); //默认情况下显示到网页的内容不会换行,需替换换行符\r\n -> <br/> $con = str_replace("\r\n", "<br/>", $con); echo "$con"; //关闭指针 fclose($fp); echo "<br><br>******第二种读取方法,循环读取(适用于大文件)********<br>"; $fp = fopen($filename, "r"); //设置buffer一次读取1024个字节 $buffer = 1024; //判断文件指针是否到了文件结束的位置 while (!feof($fp)) { //读 $con = fread($fp, $buffer); //替换换行符 $con = str_replace("\r\n", "<br/>", $con); echo "$con"; } //关闭指针 fclose($fp); echo "<br><br>******第三种读取方法********<br>"; $con = file_get_contents($filename); //替换换行符 $con = str_replace("\r\n", "<br/>", $con); echo "$con";
结果:
3.fgets():读取一行,指针下移一行
$filename = "aa.txt"; $fp = fopen($filename, ‘r‘); while (!feof($fp)) { echo fgets($fp)."<br/>"; }
结果:
$filename = "aa.txt"; fseek($fp, 0); //将文件指针移到文件最前面 while (!feof($fp)) { echo fgets($fp)."<br/>"; }
结果:
4.getc():获取一个字符
$filename = "aa.txt"; $fp = fopen($filename, ‘r‘); while (!feof($fp)) { //获取一个中文字符,占用3个字节 echo fqetc($fp)."<br/>"; }
时间: 2024-10-09 09:58:29