6

すべてのサブディレクトリを含む、指定されたディレクトリ内の JPG ファイルの総数を取得する必要があります。サブサブディレクトリはありません。

構造は次のようになります。

dir1/
2ファイル  
   サブディレクトリ 1/
       8ファイル

合計dir1 = 10 ファイル

dir2/
    5ファイル  
    サブディレクトリ 1/
        2ファイル  
    サブディレクトリ 2/
        8ファイル

合計dir2 = 15 ファイル

私はこの関数を持っていますが、最後のサブディレクトリ内のファイルのみをカウントし、合計が実際のファイル量の 2 倍になるため、うまく機能しません。(最後のサブディレクトリに40個のファイルがある場合、80を出力します)

public function count_files($path) { 
global $file_count;

$file_count = 0;
$dir = opendir($path);

if (!$dir) return -1;
while ($file = readdir($dir)) :
    if ($file == '.' || $file == '..') continue;
    if (is_dir($path . $file)) :
        $file_count += $this->count_files($path . "/" . $file);
    else :
        $file_count++;
    endif;
endwhile;

closedir($dir);
return $file_count;
}
4

6 に答える 6

10

RecursiveDirectoryIteratorを使用して、このように行うことができます

<?php
function scan_dir($path){
    $ite=new RecursiveDirectoryIterator($path);

    $bytestotal=0;
    $nbfiles=0;
    foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
        $filesize=$cur->getSize();
        $bytestotal+=$filesize;
        $nbfiles++;
        $files[] = $filename;
    }

    $bytestotal=number_format($bytestotal);

    return array('total_files'=>$nbfiles,'total_size'=>$bytestotal,'files'=>$files);
}

$files = scan_dir('./');

echo "Total: {$files['total_files']} files, {$files['total_size']} bytes\n";
//Total: 1195 files, 357,374,878 bytes 
?>
于 2012-06-05T10:37:26.873 に答える
7

それを楽しむために、私はこれをまとめました:

class FileFinder
{
    private $onFound;

    private function __construct($path, $onFound, $maxDepth)
    {
        // onFound gets called at every file found
        $this->onFound = $onFound;
        // start iterating immediately
        $this->iterate($path, $maxDepth);
    }

    private function iterate($path, $maxDepth)
    {
        $d = opendir($path);
        while ($e = readdir($d)) {
            // skip the special folders
            if ($e == '.' || $e == '..') { continue; }
            $absPath = "$path/$e";
            if (is_dir($absPath)) {
                // check $maxDepth first before entering next recursion
                if ($maxDepth != 0) {
                    // reduce maximum depth for next iteration
                    $this->iterate($absPath, $maxDepth - 1);
                }
            } else {
                // regular file found, call the found handler
                call_user_func_array($this->onFound, array($absPath));
            }
        }
        closedir($d);
    }

    // helper function to instantiate one finder object
    // return value is not very important though, because all methods are private
    public static function find($path, $onFound, $maxDepth = 0)
    {
        return new self($path, $onFound, $maxDepth);
    }
}

// start finding files (maximum depth is one folder down) 
$count = $bytes = 0;
FileFinder::find('.', function($file) use (&$count, &$bytes) {
    // the closure updates count and bytes so far
    ++$count;
    $bytes += filesize($file);
}, 1);

echo "Nr files: $count; bytes used: $bytes\n";

ベース パス、検出されたハンドラー、および最大ディレクトリ深度 (無効にする場合は -1) を渡します。見つかったハンドラーは、外部で定義する関数であり、関数で指定されたパスからの相対パス名が渡されfind()ます。

それが理にかなっていて、あなたを助けることを願っています:)

于 2012-06-05T10:27:25.443 に答える
1
error_reporting(E_ALL);

function printTabs($level)
{
    echo "<br/><br/>";
    $l = 0;
    for (; $l < $level; $l++)
        echo ".";
}

function printFileCount($dirName, $init)
{
    $fileCount = 0;
    $st        = strrpos($dirName, "/");
    printTabs($init);
    echo substr($dirName, $st);

    $dHandle   = opendir($dirName);
    while (false !== ($subEntity = readdir($dHandle)))
    {
        if ($subEntity == "." || $subEntity == "..")
            continue;
        if (is_file($dirName . '/' . $subEntity))
        {
            $fileCount++;
        }
        else //if(is_dir($dirName.'/'.$subEntity))
        {
            printFileCount($dirName . '/' . $subEntity, $init + 1);
        }
    }
    printTabs($init);
    echo($fileCount . " files");

    return;
}

printFileCount("/var/www", 0);

動作確認済みです。しかし、結果のアライメントは悪く、ロジックは機能します

于 2012-06-05T11:08:59.760 に答える
0

誰かがファイルとディレクトリの総数を数えようとしている場合。

合計ディレクトリ数とサブディレクトリ数を表示/カウント

find . -type d -print | wc -l

メインディレクトリとサブディレクトリの合計ファイル数を表示/カウント

find . -type f -print | wc -l

現在のディレクトリのファイルのみを表示/カウント (サブディレクトリなし)

find . -maxdepth 1 -type f -print | wc -l

現在のディレクトリ内のディレクトリとファイルの合計を表示/カウントします (サブディレクトリはありません)

ls -1 | wc -l
于 2013-11-28T10:34:04.330 に答える
-3

for each ループは、より迅速にトリックを行うことができます ;-)

私が覚えているように、opendir は RecursiveIterator 、 Traversable 、 Iterator 、 SeekableIterator クラスである SplFileObject クラスから派生しているため、SPL 標準 PHP ライブラリを使用してサブディレクトリでも画像全体を取得する場合、while ループは必要ありません。 .

しかし、私はPHPをしばらく使っていなかったので、間違いを犯したかもしれません.

于 2012-06-05T10:14:38.327 に答える