Search code examples
clinuxposixtemporary-directory

Reliable way to create temporary directory


I'm writing tests for a library that need to create a directories to test some functional it should provide. I did some research and found that there is a library function:

#include <stdio.h>
char *tmpnam(char *s);

And it is possible to call it with NULL to unique path. The problem is the linker warns me as follows:

warning: the use of `tmpnam' is dangerous, better use `mkstemp'

Also as suggested in this answer to use the function. But this hardcoding /tmp in the beginning looks strage. Also checking the environment variables TMP, TMPDIR, etc looks complicated.

Maybe there is some POSIX function which checks theses variables for me? Also is there any other pitfalls of using tmpnam except shared static buffer and race conditions?


Solution

  • The tmpnam() function doesn't create a directory; it generates a file name that didn't exist at somewhere about the time it was invoked, but which may exist by the time you try to use it with mkdir(), which does create directories. There is typically a plethora of related functions for doing roughly the same job, but they're different on each platform.

    POSIX does provide mkdtemp() and mkstemp() — the former creates a directory, the latter a file; the same page documents both — where you specify the template to the function. That leaves you in charge of the directory within which the directory or file is created.

    With both mkstemp() and mkdtemp(), the directory containing the new file or directory must already exist.

    One of the primary problems with using tmpnam() is that you have essentially no control over where the file is created or what the filename looks like. Almost all the other functions give you some measure of control. Not being thread-safe is usually not a major issue — you can provide a buffer that will be used, making it thread-safe.