我正在使用 readdir 方法将文件列表从目录读取到数组。我可以知道如何读取零大小文件,因为 readdir 只会读取非零大小文件。我也想读取空文件(捕获文件名作为存在,即使它是空的)。我可以知道该怎么做吗?以下是我从目录中读取文件的方法:-
opendir (FH, $dirs) || die $! ;
my @lines = readdir (FH) ;
closedir (FH) ;
提前谢谢您。
最佳答案
首先,您不应该使用裸字目录句柄。二、-z
tells you when a file is empty 。像这样的东西应该有效:
use strict;
use warnings;
my $dirs="/whatever/dir/you/want";
opendir(my $dh,$dirs) or die $!;
#only grabbing actual files that we can read.
my @files=grep{(-f $_) and (-r $_)} map{"$dirs/$_"} readdir($dh);
closedir($dh);
foreach my $file(@files)
{
if(-z $file)
{
print "File $file is empty.\n";
}
else
{
print "File $file is not empty.\n";
}
}
事实上,正如 TLP 在注释中指出的那样,您可以使用 -s
来获取文件的大小(以字节为单位)。
关于perl - 如何在 Perl 中读取空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9205341/