Page 1 of 1
check to see if file is open before opening
Posted: Sun May 15, 2011 9:17 pm
by richh
greetings all....
I am in the process of trying to figure out if a file is open before i attempt to access it.
from the dictionary, I see that openfiles is what I want to use; however, I am not sure how to apply it to files that was not opened from LC.
could someone point me in the right direction?
thank you in advance.
Re: check to see if file is open before opening
Posted: Mon May 16, 2011 4:38 am
by jacque
You can do it by checking for errors:
open file "notMyFile.txt"
if the result is not empty then -- couldn't open it
... do whatever you need
end if
Or you can use the "try" structure:
try
open file "notMyFile.txt"
catch tErr
answer tErr -- or whatever
end try
I don't know of any native way to check the file's status without first trying to open it. There's probably a shell command that would do it though.
Re: check to see if file is open before opening
Posted: Tue May 17, 2011 12:37 am
by Mark
Hi Jacque,
I couldn't get your suggestions to work. However, the openFiles function contains a list of files that are currently open in LiveCode.
Best regards,
Mark
Re: check to see if file is open before opening
Posted: Tue May 17, 2011 3:14 am
by jacque
The OP wants to know if a file is open that has not been opened in LC. The only way I know to do that is to try and open it. If it is already open by another app, and if the original app has locked it in use, the result will contain "can't open file". Some files are opened by apps without a lock; those will open sucessfully in LC. BBEdit, for example, allows other apps to open the same file it already has open.
Re: check to see if file is open before opening
Posted: Tue May 17, 2011 4:04 pm
by FourthWorld
jacque wrote:The OP wants to know if a file is open that has not been opened in LC. The only way I know to do that is to try and open it. If it is already open by another app, and if the original app has locked it in use, the result will contain "can't open file".
In recent years I've started making good use of LiveCode's sysError function to get more specific info about file I/O errors than LiveCode's result provides by itself, e.g.:
Code: Select all
open file tMyFile
if the result is not empty then
answer the result &" (" & sysError() &")"
end if
The sysError function returns an integer which corresponds to the OS error code for the specific issue encountered. I've found this helpful in distinguishing whether a file can't be opened because it doesn't exist or because it's already open by another process, for example.
The really diligent programmer can include a lookup table of OS codes to provide more specific feedback if needed, or to provide additional options to the user based on the specific circumstances.