forked from Sovos-Compliance/convey-public-libs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Tempstr.pas
113 lines (98 loc) · 2.43 KB
/
Tempstr.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
{ This class implements a temporary file stream }
unit TempStr;
interface
uses
Classes;
type
TTempFileStream = class (TFileStream)
private
FFileName : string;
FPrefix: string;
function CreateTempFile(const APrefix : string): string;
procedure AddToList;
public
constructor Create (const Directory : string);
constructor CreatePrefix(const APrefix: string; Dummy: Integer = 0); // Dummy added to avoid C++ warning
destructor Destroy; override;
property FileName : string read FFileName;
property Prefix: string read FPrefix;
end;
TVolatileTempFileStream = class (TTempFileStream)
public
destructor Destroy; override;
end;
var
TmpFileList : TThreadList;
implementation
uses
SysUtils, Windows, Types;
function TTempFileStream.CreateTempFile(const APrefix : string): string;
var
TempPath, TempName : PChar;
n, i : integer;
begin
FPrefix := APrefix;
TempPath := StrAlloc (Max_Path);
try
GetTempPath (Max_Path, TempPath);
TempName := StrAlloc (Max_Path);
try
i := 0;
repeat
n := GetTempFileName (TempPath, PChar (APrefix), 0, TempName);
if n = 0
then raise Exception.Create ('Error getting temp file name');
Result := StrPas (TempName);
sleep (i * 100);
inc (i);
if i > 10
then raise Exception.Create ('Error getting temp file name. It couldn''t create the file on the temp folder');
until FileExists (Result);
finally
StrDispose (TempName);
end;
finally
StrDispose (TempPath);
end;
end;
constructor TTempFileStream.Create;
var
Dir : string;
i : integer;
begin
Dir := ExtractFilePath (Directory);
i := 0;
repeat
FFileName := Format ('%s%.8d.tmp', [Dir, i]);
inc (i);
until not FileExists (FFileName);
inherited Create (FFileName, fmCreate or fmOpenReadWrite);
AddToList;
end;
constructor TTempFileStream.CreatePrefix(const APrefix: string; Dummy: Integer
= 0);
begin
FPrefix := APrefix;
FFileName := CreateTempFile (APrefix);
inherited Create (FFileName, fmOpenReadWrite);
AddToList;
end;
procedure TTempFileStream.AddToList;
begin
TmpFileList.Add (self);
end;
destructor TTempFileStream.Destroy;
begin
TmpFileList.Remove (self);
inherited;
end;
destructor TVolatileTempFileStream.Destroy;
begin
inherited;
DeleteFile (PChar (FileName));
end;
initialization
TmpFileList := TThreadList.Create;
finalization
FreeAndNil (TmpFileList);
end.