awk 'BEGIN {sum=0} {sum+=$5;} END {print sum}' # 4947228
ls -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 /etc
if ($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; // 899768
echo 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如何使用递归来计算一个目录中所有文件的大小 (代码)的详细内容,更多请关注php中文网其它相关文章!
网站建设是一个广义的术语,涵盖了许多不同的技能和学科中所使用的生产和维护的网站。
关键词:php如何运用递归来计算一个目录中所有文件的大小 (代码)