I need to know, whether or not a particular file is opened by another process.
So I wrote the following small function, which works correctly as far as I can see (tested on Windows XP x86):
Code: Select all
Procedure.i FileIsClosed (fileName$)
; returns #False if the file does not exist, or if it is opened by another process;
; #True otherwise
;
; Note: By passing zero as 3rd parameter for CreateFile_(),
; we request *exclusive* access to the respective file.
; This fails if the file is already open.
; <http://msdn.microsoft.com/en-us/library/aa363858%28v=vs.85%29.aspx>
; <http://msdn.microsoft.com/en-us/library/aa363874%28v=vs.85%29.aspx>
Protected handle
handle = CreateFile_(@fileName$, #GENERIC_READ, 0, #Null, #OPEN_EXISTING, #FILE_ATTRIBUTE_NORMAL, #Null)
If handle = #INVALID_HANDLE_VALUE
ProcedureReturn #False
Else
CloseHandle_(handle)
ProcedureReturn #True
EndIf
EndProcedure
;-- Demo
Define TestFile$ = "Test.txt"
; Test #1
CreateFile(0, TestFile$)
Debug FileIsClosed(TestFile$) ; should display 0
; Test #2
CloseFile(0)
Debug FileIsClosed(TestFile$) ; should display 1
Regards, Little John