首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在目录中找到最新创建的文件?

如何在目录中找到最新创建的文件?
EN

Stack Overflow用户
提问于 2008-11-30 09:35:29
回答 4查看 38.3K关注 0票数 22

在Perl中有没有一种很好的方法可以在目录中找到最新的文件(根据修改日期最新)?

到目前为止,我所做的是搜索我需要的文件,对于每个文件,获取它的修改时间,将其放入一个包含文件名和修改时间的数组中,然后对其进行排序。

一定有更好的办法。

EN

回答 4

Stack Overflow用户

发布于 2008-11-30 17:26:00

你不需要把所有的修改时间和文件名都保存在一个列表中,你可能也不应该这样做。你只需要查看一个文件,看看它是否比你之前看到的最旧的文件更旧:

{
    opendir my $dh, $dir or die "Could not open $dir: $!";

    my( $newest_name, $newest_time ) = ( undef, 2**31 -1 );

    while( defined( my $file = readdir( $dh ) ) ) {
        my $path = File::Spec->catfile( $dir, $file );
        next if -d $path; # skip directories, or anything else you like
        ( $newest_name, $newest_time ) = ( $file, -M _ ) if( -M $path < $newest_time );
    }

    print "Newest file is $newest_name\n";
}
票数 15
EN

Stack Overflow用户

发布于 2008-11-30 09:51:37

您可以尝试使用外壳的ls命令:

@list = `ls -t`;
$newest = $list[0];
票数 11
EN

Stack Overflow用户

发布于 2008-11-30 09:52:25

假设您知道要查找的$DIR

opendir(my $DH, $DIR) or die "Error opening $DIR: $!";
my %files = map { $_ => (stat("$DIR/$_"))[9] } grep(! /^\.\.?$/, readdir($DH));
closedir($DH);
my @sorted_files = sort { $files{$b} <=> $files{$a} } (keys %files);
# $sorted_files[0] is the most-recently modified. If it isn't the actual
# file-of-interest, you can iterate through @sorted_files until you find
# the interesting file(s).

包装readdirgrep会过滤掉".“和"..“UNIX(-ish)文件系统中的特殊文件。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/328673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档