简体   繁体   中英

How to check if a file is already in use in Windows environment

I have a small script to read from a directory in which files are going to copied to a specific folder. My script will read from the file and check whether we have received all the files that have been successfully copied.

As soon as all the files are received the next set of jobs are triggered, which process those files.

I am using the normal Input operator to read the file:

if(open(FILE,abc.txt))
  print "it opened \n";
} else {
  print "it did not open \n";
}

The above method didn't work and also the read write ( +< ) didn't work. Why?

try this if you want to check whether a file exists:

if ( -e 'abc.txt' )
{
  print "file exists\n";
}

If you are looking to check whether the file is available for read/write access ( ie ensure that another process writing the file is does not have a lock within a windows environment ) most crudely you can catch the unable to open file condition:

open(INFO,      "+<datafile") || warn("can't open datafile: $!");

In windows I believe that Determine whether a file is in use in Perl on Windows discusses how to catch the failure however that appears a little crude.

The approach at https://stackoverflow.com/a/4200474/5182165 looks more satisfying to me.

I would suggest looking at fileno() or fcntl or include lsof in your searches for more detail.

You may also want to look at flock() as described at http://docs.activestate.com/activeperl/5.8/lib/pods/perlopentut.html#file_locking

Another interesting approach is to watch the directory for file changes using Win32::ChangeNotify as discussed at Windows - Using perl monitor a directory for a new file drop/creation

Or you could use Win32::File::Object to check whether the file has an OFFLINE status as per http://codeverge.com/perl.beginners/win32-file-attribs-example/144600

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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