首页 > 代码库 > Php处理大文件-分割和合并

Php处理大文件-分割和合并

分割文件

/*
   * 分割文件 
   * 默认大小 2M=10485760/5
   */
  function file_split($file,$block_size=10485760/5)
  {
       $block_info=array();
       $size=filesize($file);
       $i=0;
       while($size>0){
           $block_info[]=array(
               ‘size‘=>($size>=$block_size?$block_size:$size),
               ‘file‘=>str_replace(‘.txt‘, ‘‘,$file).‘.‘.($i++).‘.txt‘
           );
           $size-=$block_size;
       }
      
       $fp   = fopen($file,"rb");
       foreach ($block_info as $bi) {
           $handle = fopen($bi[‘file‘],"wb");
           fwrite($handle,fread($fp,$bi[‘size‘]));     
           fclose($handle);
           unset($handle);
       }
       fclose ($fp);
       unset($fp);
  }

合并文件  

  /*
   * 合并文件
   * 如果合并后的文件为 CPCUxcp111.flv.0.esplit 
   * 则 file=CPCUxcp111.flv,不包含.x.esplit后缀
   * save_file为另存为的文件名
   */
  function file_combine($file,$save_file=‘‘){
   $filename=basename($file);
   $filepath=dirname($file).‘/‘;
   $block_info=array();
   for($i=0;;$i++){
       if(file_exists($file.‘.‘.$i.‘.esplit‘) && filesize($file.‘.‘.$i.‘.esplit‘)>0){
           $block_info[]=$file.‘.‘.$i.‘.esplit‘;
       }else{
           break;
       }
   }
   if($save_file){
       $fp   = fopen($save_file,"wb");
   }else{
       $fp   = fopen($file,"wb");
   }
   foreach ($block_info as $block_file) {
       $handle = fopen($block_file,"rb");
       fwrite($fp,fread($handle,filesize($block_file)));     
       fclose($handle);
       unset($handle);
   }
   fclose ($fp);
   unset($fp);
  }

测试代码:

file_split(‘d:/demo.txt‘);
  • 1

  问题算是解决了,不过这方面有时间还应该研究一下

Php处理大文件-分割和合并