[erlang-questions] file:open with O_EXCL mode

Michael Santos michael.santos@REDACTED
Wed Jan 20 21:40:04 CET 2010

On Wed, Jan 20, 2010 at 04:53:04PM +0300, Dmitry Belayev wrote:
> Yes, I know about directories. But I have to create new files in one  
> directory without any subdirectories.
> I've looked through mailing list archive and found out that people meet  
> this problem once a year since 2004 year.
> And nothing changed since then.

Yeah, it's sort of a wtf moment, but I wonder if O_EXCL was even supported
on whatever Linux versions were commonly used in 2004 (manpage says 2.6+).

Are you allowed to use C? A linked in driver or an NIF might be an
option then. Something like (untested):

    static ERL_NIF_TERM
nif_tmpfile(ErlNifEnv *env, ERL_NIF_TERM _path)
    char path[MAXPATHLEN];
    int fd = -1;

    (void)memset(&path, '\0', sizeof(path));

    if (!my_enif_get_string(env, _path, path, sizeof(path)))
        return enif_make_badarg(env);

    errno = 0;
    if ( (fd = open(path, O_WRONLY|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR)) == -1)
        return enif_make_tuple(env, 2,
            enif_make_atom(env, "error"),
            enif_make_string(env, strerror(errno)));

    /* Unlike gen_tcp/udp, file module doesn't support passing in an {fd,FD} arg */

    return enif_make_atom(env, "ok");

Then (assuming nif_tmpfile maps to open/1):

    Tmp = "/tmp/foo.bar",
    ok = tmpfile:open(Tmp),
    {ok, FD} = file:open(Tmp, [read,write,binary]).

More information about the erlang-questions mailing list