I need to put data in a file since my other function takes a file as input. How do I create a unique filename in Erlang? Does something like unix "tempfile" exist?
I've finally had this problem -- and my user is using a mix of Windows and Linux systems, so the old tried-and-true lib:nonl(os:cmd("mktemp")) method is just not going to cut it anymore. So here is how I've approached it, both with a mktemp/1 function that returns a filename that can be used and also a mktemp_dir/1 function that returns a directory (after having created it).
Both of these do basically the same thing: we get a strongly random name as a binary, convert that to a base36 string, and append it to whatever the OS returns to us as a safe user-local temporary cache location. On a unix type system, of course, we could just use filename:join(["/tmp", Prefix, Rand]) but the unavailability of /tmp on Windows is sort of the whole point here.
6条答案
按热度按时间h9a6wy2h1#
你的意思是只生成实际的文件名吗?在这种情况下,最安全的方法是使用从now()得到的数字和你的计算机的主机名的混合(如果你有几个节点做同样的事情)。
类似于:
1szpjjfi2#
您也可以使用
TMP = lib:nonl(os:cmd("mktemp")).
umuewwlo3#
或者你可以
erlang:phash2(make_ref())
一个快速简单的唯一标识符。对于2^82个调用来说是唯一的,这对于你的目的来说应该足够了。我发现这比用节点名格式化时间戳要容易。
798qvoo84#
迟回答:我刚刚注意到test_server模块,它支持临时目录,值得一看
http://www.erlang.org/doc/man/test_server.html#temp_name-1
93ze6v8z5#
I've finally had this problem -- and my user is using a mix of Windows and Linux systems, so the old tried-and-true
lib:nonl(os:cmd("mktemp"))
method is just not going to cut it anymore.So here is how I've approached it, both with a
mktemp/1
function that returns a filename that can be used and also amktemp_dir/1
function that returns a directory (after having created it).And the directory version:
Both of these do basically the same thing: we get a strongly random name as a binary, convert that to a base36 string, and append it to whatever the OS returns to us as a safe user-local temporary cache location.
On a unix type system, of course, we could just use
filename:join(["/tmp", Prefix, Rand])
but the unavailability of/tmp
on Windows is sort of the whole point here.zazmityj6#
In OTP 24 there is not
file:ensure_dir
. So I've made something similar:For directory:
For file: