Examples have been provided and any advice for improvements is much appreciated.
UDF:
#include-once ; #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7 ; #INDEX# ======================================================================================================================= ; Title .........: LockFile ; AutoIt Version : v3.3.0.0 or higher ; Language ......: English ; Description ...: Lock a file to the current process only. Any attempts to interact with the file by another process will fail. ; Note ..........: ; Author(s) .....: guinness ; Remarks .......: The locked file handle must be closed with the LockUnlock() function after use. ; =============================================================================================================================== ; #INCLUDES# ========================================================================================================= #include <WinAPI.au3> ; #GLOBAL VARIABLES# ================================================================================================= ; None ; #CURRENT# ===================================================================================================================== ; LockErase: Erase the contents of a locked file. ; LockFile: Lock a file to the current process only. ; LockRead: Read data from a locked file. ; LockReduce: Reduce the locked file by a certain percentage. ; LockWrite: Write data to a locked file. ; LockUnlock: Unlock a file so other processes can interact with it. ; =============================================================================================================================== ; #INTERNAL_USE_ONLY#============================================================================================================ ; None ; =============================================================================================================================== ; #FUNCTION# ==================================================================================================================== ; Name ..........: LockErase ; Description ...: Erase the contents of a locked file. ; Syntax ........: LockErase($hFile) ; Parameters ....: $hFile - Handle returned by LockFile. ; Return values .: Success - True ; Failure - False, use _WinAPI_GetLastError() to get additional details. ; Author ........: guinness ; Example .......: Yes ; =============================================================================================================================== Func LockErase($hFile) _WinAPI_SetFilePointer($hFile, $FILE_BEGIN) Return _WinAPI_SetEndOfFile($hFile) EndFunc ;==>LockErase ; #FUNCTION# ==================================================================================================================== ; Name ..........: LockFile ; Description ...: Lock a file to the current process only. ; Syntax ........: LockFile($sFilePath[, $fCreateNotExist = False]) ; Parameters ....: $sFilePath - Filepath of the file to lock. ; $fCreateNotExist - [optional] Create the file if it doesn't exist (True) or don't create (False). Default is False. ; Return values .: Success - Handle of the locked file. ; Failure - Sets @error to non-zero, call _WinAPI_GetLastError() to get extended error information. ; Author ........: guinness ; Example .......: Yes ; =============================================================================================================================== Func LockFile($sFilePath, $fCreateNotExist = False) Return _WinAPI_CreateFile($sFilePath, BitOR($CREATE_ALWAYS, Int($fCreateNotExist)), BitOR($FILE_SHARE_WRITE, $FILE_SHARE_DELETE), 0, 0, 0) ; Creation = 2, Access = 2 + 4, Sharing = 0, Attributes = 0, Security = 0. EndFunc ;==>LockFile ; #FUNCTION# ==================================================================================================================== ; Name ..........: LockRead ; Description ...: Read data from a locked file. ; Syntax ........: LockRead($hFile) ; Parameters ....: $hFile - Handle returned by LockFile. ; Return values .: Success - Data read from the file. ; Failure - '' and sets @error to non-zero ; Author ........: guinness ; Example .......: Yes ; =============================================================================================================================== Func LockRead($hFile) Local $iFileSize = (_WinAPI_GetFileSizeEx($hFile) + 1), $sText = '' Local $tBuffer = DllStructCreate('byte[' & $iFileSize & ']') _WinAPI_SetFilePointer($hFile, $FILE_BEGIN) _WinAPI_ReadFile($hFile, DllStructGetPtr($tBuffer), $iFileSize, $sText) Return SetError(@error, 0, BinaryToString(DllStructGetData($tBuffer, 1))) EndFunc ;==>LockRead ; #FUNCTION# ==================================================================================================================== ; Name ..........: LockReduce ; Description ...: Reduce the locked file by a certain percentage. ; Syntax ........: LockReduce($hFile, $iPercentage) ; Parameters ....: $hFile - Handle returned by LockFile. ; $iPercentage - A percentage value to reduce the file by. ; Return values .: Success - True ; Failure - False, use _WinAPI_GetLastError() to get additional details. ; Author ........: guinness ; Example .......: Yes ; =============================================================================================================================== Func LockReduce($hFile, $iPercentage) If $iPercentage > 0 And $iPercentage < 100 Then Local $iFileSize = _WinAPI_GetFileSizeEx($hFile) * ($iPercentage / 100) _WinAPI_SetFilePointer($hFile, $iFileSize) Return _WinAPI_SetEndOfFile($hFile) EndIf Return LockErase($hFile) EndFunc ;==>LockReduce ; #FUNCTION# ==================================================================================================================== ; Name ..........: LockWrite ; Description ...: Write data to a locked file. ; Syntax ........: LockWrite($hFile, $sText) ; Parameters ....: $hFile - Handle returned by LockFile. ; $sText - Data to be written to the locked file. ; Return values .: Success - Number of bytes written to the file. ; Failure - 0 and sets @error to non-zero ; Author ........: guinness ; Example .......: Yes ; =============================================================================================================================== Func LockWrite($hFile, $sText) Local $iFileSize = _WinAPI_GetFileSizeEx($hFile), _ $iLength = StringLen($sText), _ $iWritten = 0 Local $tBuffer = DllStructCreate('byte[' & $iLength & ']') DllStructSetData($tBuffer, 1, $sText) _WinAPI_SetFilePointer($hFile, $iFileSize) _WinAPI_WriteFile($hFile, DllStructGetPtr($tBuffer), $iLength, $iWritten) Return SetError(@error, @extended, $iWritten) ; Number of bytes written. EndFunc ;==>LockWrite ; #FUNCTION# ==================================================================================================================== ; Name ..........: LockUnlock ; Description ...: Unlock a file so other applications can interact with it. ; Syntax ........: LockUnlock($hFile) ; Parameters ....: $hFile - Handle returned by LockFile. ; Return values .: Success - True ; Failure - False ; Author ........: guinness ; Example .......: Yes ; =============================================================================================================================== Func LockUnlock($hFile) Return _WinAPI_CloseHandle($hFile) EndFunc ;==>LockUnlock
Example 1: (with LockFile)
#include <Constants.au3> #include 'LockFile.au3' ; Include the LockFile.au3 UDF. Example_1() ; LockFile by guinness. Func Example_1() ; Path of the locked file. Local $sFilePath = @ScriptDir & '\Example.txt' ; Lock the file to this process alone and create if not already created. Local $hLock = LockFile($sFilePath, 1) ; Erase the contents of the locked file. LockErase($hLock) ; Write random data to the locked file. For $i = 1 To 5 LockWrite($hLock, RandomText(10) & @CRLF) Next ; Read the locked file. Local $sRead = LockRead($hLock) ; Display the contents of the locked file that was just read. MsgBox($MB_SYSTEMMODAL, '', $sRead) ; Display the current file size of the locked file. For example 60 bytes. MsgBox($MB_SYSTEMMODAL, "", _ByteSuffix(_WinAPI_GetFileSizeEx($hLock))) ; Reduce the file size by 50%. LockReduce($hLock, 50) ; Display the reduced size. This will be 50% less than before. For example 30 bytes. MsgBox($MB_SYSTEMMODAL, "", _ByteSuffix(_WinAPI_GetFileSizeEx($hLock))) ; Delete the locked file. As this is locked the deletion will fail MsgBox($MB_SYSTEMMODAL, '', 'Delete the locked: ' & _ @CRLF & _ @CRLF & _ FileDelete($sFilePath) & ' (this will return 0, as the file is currently locked.)') ; Unlock the locked file. LockUnlock($hLock) ; Delete the file as it is now unlocked. MsgBox($MB_SYSTEMMODAL, '', 'Delete the locked: ' & _ @CRLF & _ @CRLF & _ FileDelete($sFilePath) & ' (this will return 1, as the file is unlocked.)') EndFunc ;==>Example_1 Func _ByteSuffix($iBytes, $iRound = 2) ; By Spiff59 Local $iIndex, $aArray[9] = [" bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB"] While $iBytes > 1023 $iIndex += 1 $iBytes /= 1024 WEnd Return Round($iBytes, $iRound) & $aArray[$iIndex] EndFunc ;==>_ByteSuffix Func RandomText($iLength) ; Creating random text. Local $sData = '', $sRandom = '' For $i = 1 To $iLength $sRandom = Random(55, 116, 1) $sData &= Chr($sRandom + 6 * ($sRandom > 90) - 7 * ($sRandom < 65)) Next Return $sData EndFunc ;==>RandomText
Example 2: (without LockFile)
#include <Constants.au3> Example_2() ; Traditional approach to reading and writing to a file. Due to the nature of AutoIt the file isn't locked, thus allowing other processes to interact with the file. Func Example_2() ; Path of the locked file. Local $sFilePath = @ScriptDir & '\Example.txt' ; Lock the file to this process alone and create if not already created. This is writing mode. Local $hLock = FileOpen($sFilePath, 2) ; Erase the contents of the locked file. FileWrite($hLock, '') ; Write random data to the locked file. For $i = 1 To 5 FileWrite($hLock, RandomText(10) & @CRLF) Next ; Close the file handle and another handle to read the file contents. FileClose($hLock) $hLock = FileOpen($sFilePath, 0) ; Read the locked file. Local $sRead = FileRead($hLock) ; Display the contents of the locked file that was just read. MsgBox($MB_SYSTEMMODAL, '', $sRead) ; Delete the locked file. As this is locked is not locked by AutoIt the file will be deleted. MsgBox($MB_SYSTEMMODAL, '', 'Delete the locked: ' & _ @CRLF & _ @CRLF & _ FileDelete($sFilePath) & ' (this will return 1, as the file is''t locked by AutoIt due to safety measures in place.)') ; Unlock the locked file. FileClose($hLock) EndFunc ;==>Example_2 Func RandomText($iLength) ; Creating random text. Local $sData = '', $sRandom = '' For $i = 1 To $iLength $sRandom = Random(55, 116, 1) $sData &= Chr($sRandom + 6 * ($sRandom > 90) - 7 * ($sRandom < 65)) Next Return $sData EndFunc ;==>RandomText
LockFile.zip 3.35K
9 downloadsPrevious download: 440+
Edited by guinness, Yesterday, 11:02 PM.








