-1

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?

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • 2
    Possible duplicate of [How to create a temporary directory in C?](https://stackoverflow.com/a/37557368/608639) – jww Apr 05 '19 at 16:44

1 Answers1

1

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • I guess that if I simply specify `XXXXXX` as a template I get a new directory created in the current working directory (I tried it and it worked that way). But it did not documented in the [man page](https://linux.die.net/man/3/mkdtemp) – St.Antario Apr 05 '19 at 16:37
  • 2
    POSIX says the name must end with at least 6 X's; that name ends with (and starts with) 6 X's, so it is a valid template, and the generated name is for the current directory since there is no `/` in the path to indicate it is anywhere else. So, that should work. It's probably more conventional to use some prefix for the file to indicate which program it is that created it, but it isn't actually mandatory. – Jonathan Leffler Apr 05 '19 at 16:39