简体   繁体   English

如何使用Perl在Unix中获得文件创建时间

[英]How to get file creation time in Unix with Perl

How to get file creation time in unix with perl? 如何使用Perl在UNIX中获取文件创建时间?

I have this command which displays file's last modification time: 我有此命令,它显示文件的最后修改时间:

perl -MPOSIX -le 'print strftime "%d %b %Y %H:%M ".$_, localtime((lstat)[9]) for @ARGV' file.txt

There is not normally file creation time in UNIX. 在UNIX中,通常没有文件创建时间 A new xstat() interface promises support for it, but perl doesn't use it. 一个新的xstat()接口承诺支持它,但是perl不使用它。 It is possible to write an XS-based interface to gain access to it. 可以编写基于XS的接口来访问它。

In Perl on UNIX, ctime stands for Inode Change Time, which has nothing to do with file creation. 在UNIX上的Perl中, ctime代表Inode Change Time,它与文件创建无关。

According to perlport , ctime will be creation time only on Windows, but you might want to use the Win32API::File::Time::GetFileTime() since it is more explicit (and will be obvious to porters) that your program depends on creation time instead of whatever ctime contains. 根据perlportctime将仅在Windows上是创建时间,但是您可能要使用Win32API :: File :: Time :: GetFileTime(),因为它更加明确(并且对于搬运工来说很明显)是程序所依赖的时间创建时间,而不是ctime包含的时间。

You almost have it. 差不多了

You just need to pass the return value from localtime instead of the filename to strftime : 您只需要将返回值从localtime而不是文件名传递给strftime

perl -MPOSIX -e 'printf "%s %s\n", $_, strftime("%d %b %Y %H:%M", localtime((lstat)[9])) for @ARGV' file.txt

Outputs: 输出:

file.txt 10 Oct 2014 15:38

And even though it takes more code, I'd lean toward using Time::Piece and File::stat to make the code more modern and readable: 即使需要更多代码,我还是倾向于使用Time::PieceFile::stat使代码更现代,更易读:

perl -MTime::Piece -MFile::stat -e '
    printf "%s %s\n",  $_, localtime( stat($_)->mtime )->strftime("%d %b %Y %H:%M") for @ARGV
  ' file.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM