Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Check if File is Open/Closed and by which user

Tags:

file

r

excel

xlsx

I have a document that is used by multiple people, and we have to continually check if the file is in use and by who.

I was wondering if there is anyway in R that I could obtain the status of an .xlsx file, if it is closed or open, and who has the file open.

I would then push this result to a HTML page which would refresh on a regular basis, this should then remove the need for the manual checking.

like image 756
Methexis Avatar asked Jan 05 '15 12:01

Methexis


1 Answers

Here is a starting point you might consider. This option is using C code you can compile in with R Cmd and call from R.

In a file "islocked.c" paste this:

#include <stdio.h>
#include <share.h>

void testLock(int *locked, char **filename)
{
    FILE *stream;
    if( (stream = _fsopen( *filename, "wt", _SH_DENYWR )) != NULL ) {
        fclose( stream );
        *locked = 0;
    } else {
        *locked = 1;
    }
}

Open a command prompt (windows | find | 'cmd')
Change into the folder you saved the file above
From your command prompt c:\ type the following
"Program File\R\R-3.1.2\bin\r" CMD SHLIB islocked.c
It shouldn't throw any errors or warnings and create a .o and .dll file as a result.

Now in R:
dyn.load('c:\pathtothe_c_file\islocked.dll') result->.C('testLock', islocked=as.integer(0), filename="d:\tools\r\test.dll") result$islocked [1] 1

The dll is locked by R so this should return 1. Try the .o file and it should return 0. There is an API in Windows 7 and newer called IFileInUse which may return the process and possibly the user that has the file open that you might review if you need more information.

IsFileInUse API: http://msdn.microsoft.com/en-us/library/windows/desktop/ee330722%28v=vs.85%29.aspx

A utility from Microsoft that runs on a command line you can shell to from R that may produce what you need, if you are able to install tools on the server: http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx

like image 196
Tim Cederquist Avatar answered Oct 12 '22 04:10

Tim Cederquist