Creating a unique temporary file
Copyright © 2000 Ernesto De Spirito
![]() |
CreateTempFile
This function (see source code below) creates a unique file in the temporary directory and returns its
path name. The name of the file has the form "~XXXX.TMP",
where XXXX is the hexadecimal representation of a two-byte integer
(determined using the system clock).
uses SysUtils, Windows;
function CreateTempFile: TFileName;
// Creates a temporal file and returns its path name
var
TempFileName: array [0..MAX_PATH-1] of char;
begin
if GetTempFileName(PChar(GetTempDir), '~', 0, TempFileName) = 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
Result := TempFileName;
end;
Sample call
This temporary file is not deleted automatically by Windows, so your application is responsible for deleting the files created with this function when it no longer needs them. For example you can use a code like this:procedure TForm1.Button1Click(Sender: TObject);
var
TempFileName: TFileName;
begin
TempFileName := CreateTempFile;
try
// Open the file
// Use the file
// Close the file
except
try
// Close the file if opened
finally
SysUtils.DeleteFile(TempFileName);
end;
end;
end;
![]() |



