PHP函数封装之文件读写截断

  • A+
所属分类:PHP

读取函数

  1. //文件读写函数
  2. function read_file(string $filename){
  3.     //检测文件是否存在,且有读的权限
  4.     if (is_file($filename) && is_readable($filename)){
  5.         return file_get_contents($filename);
  6.     }
  7.     return false;
  8. }
  9. echo read_file('test_read.txt');
  10. //读取文件中的内容到数组中
  11. function read_file_array(string $filename,bool $skip_empty_lines=false){
  12.     //判断文件是否存在,且有读的权限
  13.     if (is_file($filename) && is_readable($filename)){
  14.         if ($skip_empty_lines){
  15.             return file($filename,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
  16.         }else{
  17.             return file($filename);
  18.         }
  19.     }
  20.     return false;
  21. }
  22. print_r(read_file_array('test_read.txt'));

 

写入函数

  1. //向文件中写入内容,且判断是否需要清空文件中的内容
  2. function write_file(string $filename,$data,$clearFlag=false){
  3.     //dirname — 返回路径中的目录部分
  4.     $dirname =dirname($filename);
  5.     //检测目标路径是否存在
  6.     if (!file_exists($dirname)){
  7.         mkdir($dirname,'0777',true);
  8.     }
  9.     //检测文件是否存在并且可读
  10.     if(is_file($filename) && is_readable($filename)){
  11.         //通过判断文件大小,来判断是否有内容
  12.         if (filesize($filename) >0){
  13.             //读取文件中的内容
  14.             $srcData = file_get_contents($filename);
  15.         }
  16.     }
  17.   //判断内容是否是数组或者对象
  18.     if (is_array($data) || is_object($data)){
  19.         //序列化数据
  20.         $data =serialize($data);
  21.     }
  22. //判断是否清空源文件中的内容
  23.     if (!$clearFlag){
  24.         //拼装之前的内容到一起
  25.         $data=$srcData.$data;
  26.     }
  27.     //向文件中写入内容
  28.     if (file_put_contents($filename,$data) !==false){
  29.         return true;
  30.     }else{
  31.         return false;
  32.     }
  33. }
  34. write_file('4.php','lee',true);

 

截断内容函数

  1. //截断内容
  2. function truncate_file(string $filename,int $length){
  3.     if (is_file($filename) && is_writable($filename)){
  4.         //以r+(读写)的方式打开文件
  5.         $handle = fopen($filename,'r+');
  6.         //判断长度的大小,三元操作符
  7.         $length = $length <0?0:$length;
  8.         ftruncate($handle,$length);
  9.         fclose($handle);
  10.         return true;
  11.     }
  12.     return false;
  13. }
  14. truncate_file('test_read.txt',6);
李金龙

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: