TmpFile
Posted: Sat Mar 04, 2023 4:38 am
I looked at how it was done in AutoIt3 and did the same on PureBasic.
Simplified code
more
Looked at this function which uses the time in the filename, but it's only for Windows.
Code: Select all
EnableExplicit
Procedure.s TmpFile(sDirName$ = "", Prefix$ = "~", Ext$ = ".tmp", RandomLength = 7)
Protected TmpName$
If RandomLength <= 0 Or RandomLength > 130
RandomLength = 7
EndIf
If Not Asc(sDirName$) Or FileSize(sDirName$) = -1
sDirName$ = GetTemporaryDirectory()
; If FileSize(sDirName$) = -1
; sDirName$ = GetPathPart(ProgramFilename())
; EndIf
EndIf
If Not CheckFilename(Prefix$)
Prefix$ = "~"
EndIf
If Not CheckFilename(Ext$)
Ext$ = ".tmp"
EndIf
If Right(sDirName$, 1) <> #PS$
sDirName$ + #PS$
EndIf
If Asc(Ext$) And Left(Ext$, 1) <> "."
Ext$ = "." + Ext$
EndIf
; Create the temporary file path without writing to the selected directory
Repeat
; Create a random filename
TmpName$ = ""
While Len(TmpName$) < RandomLength
TmpName$ + Chr(Random(122, 97))
Wend
; Temporary filepath
TmpName$ = sDirName$ + Prefix$ + TmpName$ + Ext$
Until FileSize(TmpName$) = -1 ; End the loop if no file with the same name is present
ProcedureReturn TmpName$
EndProcedure
Debug TmpFile()
Code: Select all
Procedure.s TmpFile(sDirName$ = "")
Protected TmpName$
If Not Asc(sDirName$) Or FileSize(sDirName$) = -1
sDirName$ = GetTemporaryDirectory()
EndIf
If Right(sDirName$, 1) <> #PS$
sDirName$ + #PS$
EndIf
Repeat
TmpName$ = ""
While Len(TmpName$) < 7
TmpName$ + Chr(Random(122, 97))
TmpName$ + Chr(Random(90, 65))
TmpName$ + Chr(Random(57, 48))
Wend
TmpName$ = sDirName$ + TmpName$
Until FileSize(TmpName$) = -1
ProcedureReturn TmpName$
EndProcedure
Debug TmpFile()
Code: Select all
Procedure.s TmpFile(DirName$ = "")
Protected TmpName$, *mem, i, *a.Ascii
If Not Asc(DirName$) Or FileSize(DirName$) = -1
DirName$ = GetTemporaryDirectory()
EndIf
If Right(DirName$, 1) <> #PS$
DirName$ + #PS$
EndIf
*mem = AllocateMemory(7, #PB_Memory_NoClear)
If *mem
Repeat
*a = *mem
For i = 1 To 7
Select Random(2)
Case 0
*a\a = Random(122, 97)
Case 1
*a\a = Random(90, 65)
Case 2
*a\a = Random(57, 48)
EndSelect
*a + SizeOf(Ascii)
Next
TmpName$ = DirName$ + PeekS(*mem, 7, #PB_Ascii)
Until FileSize(TmpName$) = -1
FreeMemory(*mem)
EndIf
ProcedureReturn TmpName$
EndProcedure
Debug TmpFile()
Code: Select all
Debug GetTemporaryDirectory() + "~" + Hex(Random(9223372036854775807)) + ".tmp"
Debug GetTemporaryDirectory() + "~" + Hex(Date()) + Hex(Random(2147483647)) + ".tmp"