php读写文件夹

<?php

// 将第四列的uid在$uidArr中的行写入新的文件
// 参数1 读取的目录 绝对路径 以下代码为不带最后的斜线
// 参数2 写入的目录 绝对路径 以下代码为不带最后的斜线
ini_set('memory_limit', '-1');
if(!empty($argv[1]) && !empty($argv[2])){
    $readPath = $argv[1];
    $writePath = $argv[2];
}else{
    echo "readPath or writePath is empty";die;
}
function listFile($readPath, $writePath){
    $uidArr = array(111,222,333);
    $nameArr = scandir($readPath); // 返回要读目录中的文件和目录的数组
    foreach($nameArr as $name){
        $sonReadPath = $readPath.'/'.$name;
        if(is_dir($sonReadPath)){ // 是否为文件夹
            if($name=='.' || $name=='..'){
               continue;
            }
            $sonWritePath = $writePath.'/'.$name;
            if (!file_exists($sonWritePath)){ // 写入目录没有对应的子文件夹则创建
                mkdir($sonWritePath, 0777, true);
            }else{ // 写入目录有对应的子文件夹则清空
                delDir($sonWritePath.'/');
            }
            // 新的读目录和写目录继续以上逻辑
            listFile($sonReadPath, $sonWritePath);
        }else{ // 为文件
            $f1 = fopen($sonReadPath, 'r');
            $f2 = fopen($writePath.'/'.$name, 'w');
            while (!feof($f1)){ // 循环读取每行
                $line = fgets($f1);
                $arr = explode("\t", $line);
                if(isset($arr[3]) && in_array($arr[3], $uidArr)){
                    $line = implode("\t", $arr);
                    fputs($f2, $line);
                }
            }
            fclose($f2);
            fclose($f1);
        }
    }
}

// 清空文件夹 绝对路径并带有最后的斜线
function delDir($path){
    if(is_dir($path)){
        $p = scandir($path);
        foreach($p as $val){
            if($val !="." && $val !=".."){
                if(is_dir($path.$val)){
                    delDir($path.$val.'/');
                    @rmdir($path.$val.'/');
                }else{
                    unlink($path.$val);
                }
            }
        }
    }
}

listFile($readPath, $writePath);

?>
发布了45 篇原创文章 · 获赞 10 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/sosemseo/article/details/105559953
今日推荐