<?php
/* 文件的基本操作:
1.打开和关闭
fopen、fclose
2.读取文件内容
fread、file_get_contents、fgets、fgetc、file、readfile
3.访问远程文件
方法很多了,不一一列举
4.移动文件指针
ftell、fseek、rewind
5.文件的锁定机制
flock
*/
abstract class FileAction{
public $filename;
public function __construct($filename){
$this->filename = $filename;
$this->path = $path;
}
abstract function fileopen();
abstract function filefwrite();
}
class FileOpenAction extends FileAction{
function fileopen(){
$handle = fopen($this->filename,"r");
return $handle;
}
function filefwrite(){
$textname = 'data.txt';
$handle = fopen($textname,"r")or die('打开文件失败');//打开文件,如果文件不存在可以创建文件
$content = fread($handle,10);//读取文件中前50个字符,fopen第二个参数为r、r+才能读取
$content1 = fread($handle,filesize($textname));//读取全部内容的方法
for($row=0;$row<10;$row++){
fwrite($handle,$row.nl2br(":循环写入\n"));
}
fclose($handle);
echo $content1;
readfile($textname);//readfile不用fopen打开,可以读取整个文件,然后立即输入到缓冲区中,将文件输出到浏览器中
print_r(file($textname));//file函数很重要,file函数可以把整个文件读取到一个数组中,如果有换行符就可以整合成数组
//另外一种写法
$filename = 'data1.txt';
$data = '另一种写法';
for($row=0;$row<10;$row++){
$data.=$row.":This is test".nl2br("\n");
}
file_put_contents($filename,$data);
//file_get_contents方法要比fread上面的方法性能好的多
echo file_get_contents("data.txt");
}
}
$open = new FileOpenAction('file1.php');
$open->fileopen();
$open->filefwrite();
?>