如何使用 File::stat 模块在 Perl 中查找文件夹大小?

How to find folder size in Perl using File::stat module?

下面是使用 File::stat 模块查找文件大小的 Perl 脚本:

#!/usr/bin/perl

use strict;
use warnings;

use File::stat;

my $directory = "/home/dinkar/index.html";

my $dirStats  = stat($directory);
my $size      = $dirStats->size;

printf("Size of %s: %d", $directory, $size);
printf("\n");

我得到了正确的文件大小输出,但此代码无法找到文件夹大小。它只计算文件夹内的文件数。例如,如果文件夹 /home/dinkar 中有八个文件,我得到的文件夹输出为 8,这是错误的。

我想使用 File::stat module 在 Perl 中查找文件夹大小。请帮忙。

File::stat 模块只不过是内置 stat 运算符的更易于访问的接口。由于 stat 不提供检索目录 "size" 的方法,File::stat.

也不提供

您所说的目录大小是指它包含的所有文件的大小总和,或者在它下面的递归目录中的所有文件的大小总和。您必须手动计算,最好的工具可能是 File::Find.

本程序演示

use strict;
use warnings;
use 5.010;

use File::Find;

my $total;

find(sub { $total += -s if -f }, '/home/dinkar');

say $total;

如果要测量的文件很多,那么这可能需要几秒钟才能完成。

这是一个 linux,不是 Perl 问题:linux 中的文件夹只是一个包含文件名的文件,因此大小就是这些名称的大小,正如您注意到了。

http://tldp.org/LDP/intro-linux/html/sect_03_01.html

A Linux system, just like UNIX, makes no difference between a file and a directory, since a directory is just a file containing names of other files

如果你想要目录中所有文件的大小,你将不得不通过阅读所有文件 with readdir 并总结找到的大小来自己总结 和File::stat