PDA

View Full Version : cross-platform temp filename generator?



paul_nicholls
12-10-2009, 10:39 PM
Hi all,
I was wondering if there is a cross-platform method of generating a temporary filename, one that would work with Delphi AND freepascal (whatever platform)?

I currently have tried coding this (not run it yet though):

Function TPackFile.GetTemporaryFileName : AnsiString;
Const
cValidChars = 'abcdefghijklmnopqrztuvwxyz1234567890!@#$%()_+[]{}';
cValidCharsLen = Length(cValidChars);
Var
i : Integer;
Seed : LongInt;
Begin
Seed := RandSeed;
Randomize;
SetLength(Result,Random(20) + 10);
For i := 1 To Length(Result) Do Result[i] := cValidChars[Random(cValidCharsLen) + 1];
RandSeed := Seed;
End;

Does this code seem ok to generate random filenames?

cheers,
paul

KidPaddle
13-10-2009, 06:18 AM
I missing checking if file already exists, like


if FileExists(Result) then Result := GetTemporaryFileName()

and maybe it was useful to add a suffix as optional parameter to function.

Thomas

User137
13-10-2009, 05:42 PM
I see 2 things that may not work as intended:

1) Randomize is not supposed to be called more than once per program runtime, it uses GetTickCount for seed if i recall, and if you call this function more than once per 1 millisecond it will generate same name.
I suggest scrapping all seed and Randomize() code out.

2) I don't think setlength() is proper use for strings, consider
(init)
Result := '';
(for loop)
Result := Result+cValidChars[Random(cValidCharsLen) + 1];

arthurprs
13-10-2009, 07:56 PM
I see 2 things that may not work as intended:

1) Randomize is not supposed to be called more than once per program runtime, it uses GetTickCount for seed if i recall, and if you call this function more than once per 1 millisecond it will generate same name.
I suggest scrapping all seed and Randomize() code out.

2) I don't think setlength() is proper use for strings, consider
(init)
Result := '';
(for loop)
Result := Result+cValidChars[Random(cValidCharsLen) + 1];


setlength is ok for strings

paul_nicholls
13-10-2009, 09:32 PM
Thanks for the hints/tips people :)
cheers,
Paul