如果文件是可写/可移动的,请在Perl和Windows中查找

时间:2015-02-24 15:51:35

标签: perl file winapi change-notification

我想在Windows下为Perl构建 Watch-Dog 以获取 Hot-Folder (我可以称之为 Folder-Watch 或者,嗯,可能要好得多: Hot-Dog )。 到目前为止,我使用Win32::ChangeNotify成功完成了这项工作(参见下面的示例)。

但正如您可能猜测阅读源代码时,当$watchdir中文件的复制/创建过程尚未完成时,移动过程想要完成时遇到问题(没有这样的文件或目录)。

use Win32::ChangeNotifier;
use File::Copy qw(move);

my $notify = Win32::ChangeNotify->new($watchdir, 0, "FILE_NAME");
while (1) {
  if ($notify->wait(1_000)) {  # 1-second wait cycle
    notify->reset;
    @foundfiles = File::get_by_ext($watchdir, "csv");  # search and return files in $watchdir with extension "csv"
    print "Something has happened! (del/ren/create)\n";
    foreach (@foundfiles) {
      move($watchdir.$_, $someotherdir.$_) or die "Fehler: $!"; 
    }
    @foundfiles = ();
  }
}

有没有办法自动确定文件是否准备就绪,即最终是否已创建/复制?

我在考虑像

这样的东西
while (1) {
  move $file if (-w $file)  # writeable
  wait(1)
}

但这似乎不适用于Windows。我需要在Windows和Perl下解决这个问题。除此之外,我愿意接受建议。

1 个答案:

答案 0 :(得分:1)

是的!我解决了它(感谢Сухой27)!

在移动文件之前插入以下代码:

while (1) {
    last if writeable($path_in.$_);
    print "-";
    $| = 1;
    sleep(1);
}

......而writeable指的是这个小小的海洋:

sub writeable {
    return open(my $file, ">>", shift);
}

谢谢,祝你有个愉快的一天! : - )