Creating temporary files and directories

by Jon Ripley, August 2007

The FNtempfile function creates and returns the name of a unique file in the current temporary directory. You should ensure that you delete this file when you no longer require it.

        file$ = FNtempfile
        REM ...
        SYS "DeleteFile", file$


The FNtempdir function creates and returns the name of a unique directory in the current temporary directory. You should ensure that you delete this directory when you no longer require it.

        dir$ = FNtempdir
        REM ...
        SYS "RemoveDirectory", dir$


The “RemoveDirectory” call requires that the directory to be deleted is empty. To delete a non-empty directory use the PROCremovedirectory function as demonstrated:

        dir$ = FNtempdir
        REM ...
        PROCremovedirectory(dir$)


The code for the FNtempfile, FNtempdir and PROCremovedirectory functions referenced in this article are listed below:

        DEF FNtempfile
        LOCAL T%
        DIM T% LOCAL 255
        SYS "GetTempPath", 256, T%
        SYS "GetTempFileName", $$T%, "tmp", 0, T%
        = $$T%
 
        DEF FNtempdir
        LOCAL T%
        DIM T% LOCAL 255
        SYS "GetTempPath", 256, T%
        SYS "GetTempFileName", $$T%, "tmp", 0, T%
        SYS "DeleteFile", $$T%
        SYS "CreateDirectory", $$T%, 0
        IF $$T% > "" $$T% += "\"
        = $$T%
 
        DEF PROCremovedirectory(D$)
        IF D$ = "" THEN ENDPROC
        LOCAL shfo{}
        DIM shfo{hWnd%, wFunc%, pFrom%, pTo%, fFlags%, fAborted%, hNameMaps%, sProgress%}
        IF RIGHT$(D$,1) = "\" THEN D$ = LEFT$(D$)
        D$ += CHR$0 + CHR$0
        shfo.hWnd% = @hwnd%
        shfo.wFunc% = 3
        shfo.pFrom% = !^D$
        shfo.fFlags% = 20
        SYS "SHFileOperation", shfo{}
        ENDPROC


The string “tmp” passed to “GetTempFileName” is a prefix for the temporary file name which you may change to any three character string, perhaps to be distinctive to your application.