File
File
#include "Array.au3"
#include "FileConstants.au3"
#include "StringConstants.au3"
; #INDEX#
===================================================================================
====================================
; Title .........: File
; AutoIt Version : 3.3.14.2
; Language ......: English
; Description ...: Functions that assist with files and directories.
; Author(s) .....: Brian Keene, Michael Michta, erifash, Jon, JdeB, Jeremy Landes,
MrCreatoR, cdkid, Valik, Erik Pilsits, Kurt, Dale, guinness, DXRW4E, Melba23
;
===================================================================================
============================================
; #CURRENT#
===================================================================================
==================================
; _FileCountLines
; _FileCreate
; _FileListToArray
; _FileListToArrayRec
; _FilePrint
; _FileReadToArray
; _FileWriteFromArray
; _FileWriteLog
; _FileWriteToLine
; _PathFull
; _PathGetRelative
; _PathMake
; _PathSplit
; _ReplaceStringInFile
; _TempFile
;
===================================================================================
============================================
;
#INTERNAL_USE_ONLY#================================================================
============================================
; __FLTAR_ListToMask
; __FLTAR_AddToList
; __FLTAR_AddFileLists
;
===================================================================================
============================================
; #FUNCTION#
===================================================================================
=================================
; Author ........: Tylo <tylo at start dot no>
; Modified.......: Xenobiologist, Gary, guinness, DXRW4E
;
===================================================================================
============================================
Func _FileCountLines($sFilePath)
Local $hFileOpen = FileOpen($sFilePath, $FO_READ)
If $hFileOpen = -1 Then Return SetError(1, 0, 0)
; #FUNCTION#
===================================================================================
=================================
; Author ........: Brian Keene <brian_keene at yahoo dot com>
; Modified.......:
;
===================================================================================
============================================
Func _FileCreate($sFilePath)
Local $hFileOpen = FileOpen($sFilePath, BitOR($FO_OVERWRITE, $FO_CREATEPATH))
If $hFileOpen = -1 Then Return SetError(1, 0, 0)
; #FUNCTION#
===================================================================================
=================================
; Author ........: Michael Michta
; Modified.......: guinness - Added optional parameter to return the full path.
;
===================================================================================
============================================
Func _FileListToArray($sFilePath, $sFilter = "*", $iFlag = $FLTA_FILESFOLDERS,
$bReturnPath = False)
Local $sDelimiter = "|", $sFileList = "", $sFileName = "", $sFullPath = ""
; Check parameters for the Default keyword or they meet a certain criteria
$sFilePath = StringRegExpReplace($sFilePath, "[\\/]+$", "") & "\" ; Ensure a
single trailing backslash
If $iFlag = Default Then $iFlag = $FLTA_FILESFOLDERS
If $bReturnPath Then $sFullPath = $sFilePath
If $sFilter = Default Then $sFilter = "*"
; #FUNCTION#
===================================================================================
=================================
; Author ........: Melba23 - with credits for code snippets to Ultima, Partypooper,
Spiff59, guinness, wraithdu
; Modified ......:
;
===================================================================================
============================================
Func _FileListToArrayRec($sFilePath, $sMask = "*", $iReturn = $FLTAR_FILESFOLDERS,
$iRecur = $FLTAR_NORECUR, $iSort = $FLTAR_NOSORT, $iReturnPath = $FLTAR_RELPATH)
If Not FileExists($sFilePath) Then Return SetError(1, 1, "")
Local $iHide_HS = 0, _
$sHide_HS = ""
; Check for H or S omitted
If BitAND($iReturn, 4) Then
$iHide_HS += 2
$sHide_HS &= "H"
$iReturn -= 4
EndIf
If BitAND($iReturn, 8) Then
$iHide_HS += 4
$sHide_HS &= "S"
$iReturn -= 8
EndIf
Local $iHide_Link = 0
; Check for link/junction omitted
If BitAND($iReturn, 16) Then
$iHide_Link = 0x400
$iReturn -= 16
EndIf
Local $iMaxLevel = 0
; If required, determine \ count for max recursive level setting
If $iRecur < 0 Then
StringReplace($sFilePath, "\", "", 0, $STR_NOCASESENSEBASIC)
$iMaxLevel = @extended - $iRecur
EndIf
; If sorting files and folders with paths then store folder name and
position of associated files in list
If $iReturn = 0 And $iSort And $iReturnPath Then
__FLTAR_AddToList($asFolderFileSectionList, $sRetPath,
$asFileMatchList[0] + 1)
EndIf
$sAttribs = ''
WEnd
WEnd
__ArrayDualPivotSort($asFileMatchList, $iFileSectionStartIndex,
$iFileSectionEndIndex)
EndIf
; Add files to return list
For $k = $iFileSectionStartIndex To
$iFileSectionEndIndex
$asReturnList[$iNextInsertionIndex] = $asFileMatchList[$k]
$iNextInsertionIndex += 1
Next
ExitLoop
EndIf
Next
Next
EndIf
EndSwitch
Else ; No sort
; Check if any file/folders have been added
If $asReturnList[0] = 0 Then Return SetError(1, 9, "")
; Remove any unused return list elements from last ReDim
ReDim $asReturnList[$asReturnList[0] + 1]
EndIf
Return $asReturnList
EndFunc ;==>_FileListToArrayRec
;
#INTERNAL_USE_ONLY#================================================================
============================================
; Name...........: __FLTAR_AddFileLists
; Description ...: Add internal lists after resizing and optional sorting
; Syntax ........: __FLTAR_AddFileLists(ByRef $asTarget, $asSource_1, $asSource_2[,
$iSort = 0])
; Parameters ....: $asReturnList - Base list
; $asRootFileMatchList - First list to add
; $asFileMatchList - Second list to add
; $iSort - (Optional) Whether to sort lists before adding
; |$iSort = 0 (Default) No sort
; |$iSort = 1 Sort in descending alphabetical order
; Return values .: None - array modified ByRef
; Author ........: Melba23
; Remarks .......: This function is used internally by _FileListToArrayRec
;
===================================================================================
============================================
Func __FLTAR_AddFileLists(ByRef $asTarget, $asSource_1, $asSource_2, $iSort = 0)
; Correctly size root file match array
ReDim $asSource_1[$asSource_1[0] + 1]
; Simple sort root file match array if required
If $iSort = 1 Then __ArrayDualPivotSort($asSource_1, 1, $asSource_1[0])
; Copy root file match array
$asTarget = $asSource_1
; Add file match count
$asTarget[0] += $asSource_2[0]
; Correctly size file match array
ReDim $asSource_2[$asSource_2[0] + 1]
; Simple sort file match array if required
If $iSort = 1 Then __ArrayDualPivotSort($asSource_2, 1, $asSource_2[0])
; Add file match array
_ArrayConcatenate($asTarget, $asSource_2, 1)
EndFunc ;==>__FLTAR_AddFileLists
;
#INTERNAL_USE_ONLY#================================================================
============================================
; Name...........: __FLTAR_AddToList
; Description ...: Add element to [?] or [?][2] list which is resized if necessary
; Syntax ........: __FLTAR_AddToList(ByRef $asList, $vValue_0, [$vValue_1])
; Parameters ....: $aList - List to be added to
; $vValue_0 - Value to add to array - if $vValue_1 exists value
added to [?][0] element in [?][2] array
; $vValue_1 - Value to add to [?][1] element in [?][2] array
(optional)
; Return values .: None - array modified ByRef
; Author ........: Melba23
; Remarks .......: This function is used internally by _FileListToArrayRec
;
===================================================================================
============================================
Func __FLTAR_AddToList(ByRef $aList, $vValue_0, $vValue_1 = -1)
If $vValue_1 = -1 Then ; [?] array
; Increase list count
$aList[0] += 1
; Double list size if too small (fewer ReDim needed)
If UBound($aList) <= $aList[0] Then ReDim $aList[UBound($aList) * 2]
; Add value
$aList[$aList[0]] = $vValue_0
Else ; [?][2] array
$aList[0][0] += 1
If UBound($aList) <= $aList[0][0] Then ReDim $aList[UBound($aList) * 2]
[2]
$aList[$aList[0][0]][0] = $vValue_0
$aList[$aList[0][0]][1] = $vValue_1
EndIf
EndFunc ;==>__FLTAR_AddToList
;
#INTERNAL_USE_ONLY#================================================================
============================================
; Name...........: __FLTAR_ListToMask
; Description ...: Convert include/exclude lists to SRE format
; Syntax ........: __FLTAR_ListToMask(ByRef $sMask, $sList)
; Parameters ....: $asMask - Include/Exclude mask to create
; $asList - Include/Exclude list to convert
; Return values .: Success: 1
; Failure: 0
; Author ........: SRE patterns developed from those posted by various forum
members and Spiff59 in particular
; Remarks .......: This function is used internally by _FileListToArrayRec
;
===================================================================================
============================================
Func __FLTAR_ListToMask(ByRef $sMask, $sList)
; Check for invalid characters within list
If StringRegExp($sList, "\\|/|:|\<|\>|\|") Then Return 0
; Strip WS and insert | for ;
$sList = StringReplace(StringStripWS(StringRegExpReplace($sList, "\s*;\s*",
";"), $STR_STRIPLEADING + $STR_STRIPTRAILING), ";", "|")
; Convert to SRE pattern
$sList = StringReplace(StringReplace(StringRegExpReplace($sList, "[][$^.{}()
+\-]", "\\$0"), "?", "."), "*", ".*?")
; Add prefix and suffix
$sMask = "(?i)^(" & $sList & ")\z"
Return 1
EndFunc ;==>__FLTAR_ListToMask
; #FUNCTION#
===================================================================================
=================================
; Author ........: erifash <erifash [at] gmail [dot] com>
; Modified.......: guinness - Use the native ShellExecute function.
;
===================================================================================
============================================
Func _FilePrint($sFilePath, $iShow = @SW_HIDE)
If $iShow = Default Then $iShow = @SW_HIDE
Return ShellExecute($sFilePath, "", @WorkingDir, "print", $iShow)
EndFunc ;==>_FilePrint
; #FUNCTION#
===================================================================================
=================================
; Author ........: Jonathan Bennett <jon at autoitscript dot com>, Valik - Support
Windows Unix and Mac line separator
; Modified ......: Jpm - fixed empty line at the end, Gary Fixed file contains only
1 line, guinness - Optional flag to return the array count.
; : Melba23 - Read to 1D/2D arrays, guinness & jchd - Removed
looping through 1D array with $FRTA_COUNT flag.
;
===================================================================================
============================================
Func _FileReadToArray($sFilePath, ByRef $vReturn, $iFlags = $FRTA_COUNT,
$sDelimiter = "")
; Clear the previous contents
$vReturn = 0
If $iFlags = Default Then $iFlags = $FRTA_COUNT
If $sDelimiter = Default Then $sDelimiter = ""
; Check delimiter
If $sDelimiter Then
; Read file into an array
Local $aLines = FileReadToArray($sFilePath)
If @error Then Return SetError(@error, 0, 0)
If StringLen($sFileRead) Then
$vReturn = StringRegExp(@LF & $sFileRead, "(?|(\N+)\z|(\N*)
(?:\R))", 3)
$vReturn[0] = UBound($vReturn) - 1
Else
Return SetError(2, 0, 0)
EndIf
Else
$vReturn = FileReadToArray($sFilePath)
If @error Then
$vReturn = 0
Return SetError(@error, 0, 0)
EndIf
EndIf
EndIf
Return 1
EndFunc ;==>_FileReadToArray
; #FUNCTION#
===================================================================================
=================================
; Author ........: Jos van der Zande <jdeb at autoitscript dot com>
; Modified.......: Updated for file handles by PsaltyDS, @error = 4 msg and 2-
dimension capability added by Spiff59 and fixed by guinness.
;
===================================================================================
============================================
Func _FileWriteFromArray($sFilePath, Const ByRef $aArray, $iBase = Default,
$iUBound = Default, $sDelimiter = "|")
Local $iReturn = 0
; Check if we have a valid array as an input.
If Not IsArray($aArray) Then Return SetError(2, 0, $iReturn)
; Open output file for overwrite by default, or use input file handle if
passed.
Local $hFileOpen = $sFilePath
If IsString($sFilePath) Then
$hFileOpen = FileOpen($sFilePath, $FO_OVERWRITE)
If $hFileOpen = -1 Then Return SetError(1, 0, $iReturn)
EndIf
; #FUNCTION#
===================================================================================
=================================
; Author ........: Jeremy Landes <jlandes at landeserve dot com>
; Modified.......: MrCreatoR - added $iFlag parameter
;
===================================================================================
============================================
Func _FileWriteLog($sLogPath, $sLogMsg, $iFlag = -1)
Local $iOpenMode = $FO_APPEND
Local $sDateNow = @YEAR & "-" & @MON & "-" & @MDAY
Local $sTimeNow = @HOUR & ":" & @MIN & ":" & @SEC
Local $sMsg = $sDateNow & " " & $sTimeNow & " : " & $sLogMsg
; Open output file for appending to the end/overwriting, or use input file
handle if passed
Local $hFileOpen = $sLogPath
If IsString($sLogPath) Then
$hFileOpen = FileOpen($sLogPath, $iOpenMode)
EndIf
If $hFileOpen = -1 Then Return SetError(1, 0, 0)
; #FUNCTION#
===================================================================================
=================================
; Author ........: cdkid
; Modified.......: partypooper, MrCreatoR
;
===================================================================================
============================================
Func _FileWriteToLine($sFilePath, $iLine, $sText, $bOverWrite = False)
If $iLine <= 0 Then Return SetError(4, 0, 0)
If Not IsString($sText) Then
$sText = String($sText)
If $sText = "" Then Return SetError(6, 0, 0)
EndIf
If $bOverWrite = Default Then $bOverWrite = False
If Not (IsBool($bOverWrite) Or $bOverWrite = 0 Or $bOverWrite = 1) Then
Return SetError(5, 0, 0) ; For old versions.
If Not FileExists($sFilePath) Then Return SetError(2, 0, 0)
FileWrite($hFileOpen, $sData)
FileClose($hFileOpen)
Return 1
EndFunc ;==>_FileWriteToLine
; #FUNCTION#
===================================================================================
=================================
; Author ........: Valik (Original function and modification to rewrite),
tittoproject (Rewrite)
; Modified.......:
;
===================================================================================
============================================
Func _PathFull($sRelativePath, $sBasePath = @WorkingDir)
If Not $sRelativePath Or $sRelativePath = "." Then Return $sBasePath
; Check for UNC paths or local drives. We run this twice at most. The
; first time, we check if the relative path is absolute. If it's not, then
; we use the base path which should be absolute.
For $i = 1 To 2
$sPath = StringLeft($sFullPath, 2)
If $sPath = "\\" Then
$sFullPath = StringTrimLeft($sFullPath, 2)
Local $nServerLen = StringInStr($sFullPath, "\") - 1
$sPath = "\\" & StringLeft($sFullPath, $nServerLen)
$sFullPath = StringTrimLeft($sFullPath, $nServerLen)
ExitLoop
ElseIf StringRight($sPath, 1) = ":" Then
$sFullPath = StringTrimLeft($sFullPath, 2)
ExitLoop
Else
$sFullPath = $sBasePath & "\" & $sFullPath
EndIf
Next
; If this happens, we've found a funky path and don't know what to do
; except for get out as fast as possible. We've also screwed up our
; variables so we definitely need to quit.
; If $i = 3 Then Return ""
; A path with a drive but no slash (e.g. C:Path\To\File) has the following
; behavior. If the relative drive is the same as the $BasePath drive then
; insert the base path. If the drives differ then just insert a leading
; slash to make the path valid.
If StringLeft($sFullPath, 1) <> "\" Then
If StringLeft($sFullPathConst, 2) = StringLeft($sBasePath, 2) Then
$sFullPath = $sBasePath & "\" & $sFullPath
Else
$sFullPath = "\" & $sFullPath
EndIf
EndIf
; Here we re-build the path from the parts above. We skip the
; loop if we are only returning the root.
$sFullPath = $sPath
If Not $bRootOnly Then
For $i = 0 To $j - 1
$sFullPath &= "\" & $aPathParts[$i]
Next
Else
$sFullPath &= $sFullPathConst
; If we detect more relative parts, remove them by calling ourself
recursively.
If StringInStr($sFullPath, "..") Then $sFullPath =
_PathFull($sFullPath)
EndIf
; #FUNCTION#
===================================================================================
=================================
; Author ........: Erik Pilsits
; Modified.......:
;
===================================================================================
============================================
Func _PathGetRelative($sFrom, $sTo)
If StringRight($sFrom, 1) <> "\" Then $sFrom &= "\" ; add missing trailing \
to $sFrom path
If StringRight($sTo, 1) <> "\" Then $sTo &= "\" ; add trailing \ to $sTo
If $sFrom = $sTo Then Return SetError(1, 0, StringTrimRight($sTo, 1)) ;
$sFrom equals $sTo
Local $asFrom = StringSplit($sFrom, "\")
Local $asTo = StringSplit($sTo, "\")
If $asFrom[1] <> $asTo[1] Then Return SetError(2, 0, StringTrimRight($sTo,
1)) ; drives are different, rel path not possible
; create rel path
Local $i = 2
Local $iDiff = 1
While 1
If $asFrom[$i] <> $asTo[$i] Then
$iDiff = $i
ExitLoop
EndIf
$i += 1
WEnd
$i = 1
Local $sRelPath = ""
For $j = 1 To $asTo[0]
If $i >= $iDiff Then
$sRelPath &= "\" & $asTo[$i]
EndIf
$i += 1
Next
$sRelPath = StringTrimLeft($sRelPath, 1)
$i = 1
For $j = 1 To $asFrom[0]
If $i > $iDiff Then
$sRelPath = "..\" & $sRelPath
EndIf
$i += 1
Next
If StringRight($sRelPath, 1) == "\" Then $sRelPath =
StringTrimRight($sRelPath, 1) ; remove trailing \
Return $sRelPath
EndFunc ;==>_PathGetRelative
; #FUNCTION#
===================================================================================
=================================
; Author ........: Valik
; Modified.......: guinness
;
===================================================================================
============================================
Func _PathMake($sDrive, $sDir, $sFileName, $sExtension)
; Format $sDrive, if it's not a UNC server name, then just get the drive
letter and add a colon
If StringLen($sDrive) Then
If Not (StringLeft($sDrive, 2) = "\\") Then $sDrive =
StringLeft($sDrive, 1) & ":"
EndIf
If StringLen($sDir) Then
; Append a backslash to the start of the directory if required
If Not (StringLeft($sDir, 1) = "\") And Not (StringLeft($sDir, 1) =
"/") Then $sDir = "\" & $sDir
EndIf
; #FUNCTION#
===================================================================================
=================================
; Author ........: Valik
; Modified.......: DXRW4E - Re-wrote to use a regular expression; guinness - Update
syntax and structure.
;
===================================================================================
============================================
Func _PathSplit($sFilePath, ByRef $sDrive, ByRef $sDir, ByRef $sFileName, ByRef
$sExtension)
Local $aArray = StringRegExp($sFilePath, "^\h*((?:\\\\\?\\)*(\\\\[^\?\/\\]+|
[A-Za-z]:)?(.*[\/\\]\h*)?((?:[^\.\/\\]|(?(?=\.[^\/\\]*\.)\.))*)?([^\/\\]*))$",
$STR_REGEXPARRAYMATCH)
If @error Then ; This error should never happen.
ReDim $aArray[5]
$aArray[0] = $sFilePath
EndIf
$sDrive = $aArray[1]
If StringLeft($aArray[2], 1) == "/" Then
$sDir = StringRegExpReplace($aArray[2], "\h*[\/\\]+\h*", "\/")
Else
$sDir = StringRegExpReplace($aArray[2], "\h*[\/\\]+\h*", "\\")
EndIf
$aArray[2] = $sDir
$sFileName = $aArray[3]
$sExtension = $aArray[4]
Return $aArray
EndFunc ;==>_PathSplit
; #FUNCTION#
===================================================================================
=================================
; Author ........: Kurt (aka /dev/null) and JdeB
; Modified ......: guinness - Re-wrote the function entirely for improvements in
readability.
;
===================================================================================
============================================
Func _ReplaceStringInFile($sFilePath, $sSearchString, $sReplaceString,
$iCaseSensitive = 0, $iOccurance = 1)
If StringInStr(FileGetAttrib($sFilePath), "R") Then Return SetError(1, 0, -1)
; Replace strings
$sFileRead = StringReplace($sFileRead, $sSearchString, $sReplaceString, 1 -
$iOccurance, $iCaseSensitive)
Local $iReturn = @extended
; Open the file for writing and set the overwrite flag
$hFileOpen = FileOpen($sFilePath, $iFileEncoding + $FO_OVERWRITE)
If $hFileOpen = -1 Then Return SetError(3, 0, -1)
; #FUNCTION#
===================================================================================
=================================
; Author ........: Dale (Klaatu) Thompson
; Modified.......: Hans Harder - Added Optional parameters, guinness - Fixed using
non-supported characters in the file prefix.
;
===================================================================================
============================================
Func _TempFile($sDirectoryName = @TempDir, $sFilePrefix = "~", $sFileExtension =
".tmp", $iRandomLength = 7)
; Check parameters for the Default keyword or they meet a certain criteria
If $iRandomLength = Default Or $iRandomLength <= 0 Then $iRandomLength = 7
If $sDirectoryName = Default Or (Not FileExists($sDirectoryName)) Then
$sDirectoryName = @TempDir
If $sFileExtension = Default Then $sFileExtension = ".tmp"
If $sFilePrefix = Default Then $sFilePrefix = "~"
; Create the temporary file path without writing to the selected directory
Local $sTempName = ""
Do
; Create a random filename
$sTempName = ""
While StringLen($sTempName) < $iRandomLength
$sTempName &= Chr(Random(97, 122, 1))
WEnd
; Temporary filepath
$sTempName = $sDirectoryName & "\" & $sFilePrefix & $sTempName & "." &
$sFileExtension
Until Not FileExists($sTempName) ; Exit the loop if no file with the same
name is present
Return $sTempName
EndFunc ;==>_TempFile