Search code examples
perlfilewinapichange-notification

Find out in Perl and Windows if a file is writeable/ removable


I would like to build in Perl under Windows a Watch-Dog for a Hot-Folder (I might call it Folder-Watch or, hmm, probably much better: a Hot-Dog). So far I succeeded in exactly doing that, with Win32::ChangeNotify (see sample below).

But as you might guess reading the source code I ran into a problem when the moving process wants to finish when the copying/creating process of the file in $watchdir has not finished (No such file or directory).

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 = ();
  }
}

Is there a way to automatically find out if the file is ready to go, i.e. has been finally created/copied?

I was thinking about something like

while (1) {
  move $file if (-w $file)  # writeable
  wait(1)
}

but that does not seem to work under Windows. I need to solve this under Windows as well as Perl. Other than that I am open to suggestions.


Solution

  • Yes! I solved it (thanks to Сухой27)!

    Inserting the following code right before moving the file:

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

    ...whereas writeable refers to this little sub-marine:

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

    Thanks, and have a nive day! :-)