本篇文章给大家带来的内容是关于php如何使用递归来计算一个目录中所有文件的大小 (代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
sudo find /private/etc -exec ls -l {} \; | awk 'begin {sum=0} {sum+=$5;} end {print sum}' # 4947228ls -ld /etc #/etc -> private/etc
先计算出/etc目录所有文件的大小4947228
dirutil.php
<?php/** * created by phpstorm. * user: mch * date: 8/14/18 * time: 22:11 */class dirutil { public static function getsize(string $path) { $totalsize = 0; $path = realpath($path); if (!file_exists($path)) { return $totalsize; } if (!is_dir($path)) { return filesize($path); } if ($dh = opendir($path)) { while (($file = readdir($dh)) !== false) { if ($file !== "." && $file !== "..") { $abs = $path.directory_separator.$file; if (is_dir($file)) { $totalsize += self::getsize($abs); } else { $totalsize += filesize($abs); } } } closedir($dh); } return $totalsize; } public static function entryforeach(string $path, callable $callback, mixed $data = null) { $path = realpath($path); if (!file_exists($path)) { return 0; } if (!is_dir($path)) { return call_user_func($callback, $path, $data); } if ($dh = opendir($path)) { while (($file = readdir($dh)) !== false) { if ($file !== "." && $file !== "..") { $abs = $path.directory_separator.$file; if (is_dir($file)) { self::entryforeach($abs, $callback, $data); } else { call_user_func($callback, $abs, $data); } } } closedir($dh); } return 0; } public static function entryreduce(string $path, callable $callback, $init) { $acc = $init; $path= realpath($path); if (!file_exists($path)) { return $acc; } if (!is_dir($path)) { return call_user_func($callback, $acc, $path); } if ($dh = opendir($path)) { while (($file = readdir($dh)) !== false) { if ($file !== "." && $file !== "..") { $abs = $path.directory_separator.$file; if (is_dir($file)) { $acc = self::entryreduce($abs, $callback, $acc); } else { $acc= call_user_func($callback, $acc, $abs); } } } closedir($dh); } return $acc; }}
test:
// php ./dirutil.php /etcif ($argc < 2) { printf("usage: php %s [filename]\n", __file__); exit(1);}echo dirutil::getsize($argv[1]).php_eol; // 899768$dir_get_size = function($path) { $size = 0; dirutil::entryforeach($path, function($path) use (&$size) { $size += filesize($path); }); return $size;};echo $dir_get_size($argv[1]).php_eol; // 899768echo dirutil::entryreduce($argv[1], function($sum, $path) { $sum += filesize($path); return $sum;}, 0).php_eol; // 899768
相关推荐:
php递归示例 php递归函数代码
php递归创建多级目录,php递归
php递归json类实例,php递归json_php教程
以上就是php如何使用递归来计算一个目录中所有文件的大小 (代码)的详细内容。