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);

?>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值