views:

226

answers:

4

I need to put data in a file since my other function takes a file as input.

How to I create a uniq filename in Erlang?

Something like unix "tempfile", do it exist?

+4  A: 

Do you mean just generate the acutal filename? In that case the safest way would be to use a mix of the numbers you get from now() and the hostname of your computer (if you have several nodes doing the same thing).

Something like:

1> {A,B,C}=now().
{1249,304278,322000}
2> N=node().
nonode@nohost
3> lists:flatten(io_lib:format("~p-~p.~p.~p",[N,A,B,C])).
"[email protected]"
4>
Mazen Harake
Since not everyone is aware of that: calls to erlang:now() are guaranteed to return unique results each time. Quite useful property...
viraptor
Yes, very useful. There is one other thing that is very useful with this way of generating a reference; you get the nodename in there which is very useful if you want to first ensure that the id is always unique (you can treat it as a local reference) and second to know from where the reference comes from. In our system (with n nodes in the cluster and shared datatables etc) we can easily find the logs and information we need about a job using this identifier only (Node + Time).
Mazen Harake
+2  A: 

You can also use os:cmd("mktemp")

Hynek -Pichi- Vychodil
+3  A: 

Or you could do

erlang:phash2(make_ref())

for a quick and easy unique indentifier. Unique for up to 2^82 calls which should be enough.for your purposes. I find this easier than formatting a timestamp with node name for use.

Jeremy Wall
A: 

Late answer: I just noticed the test_server module which has scratch directory support, worth a look

http://erldocs.com/otp%5Fsrc%5FR13B/test%5Fserver/test%5Fserver.html?i=12

Gene T