Is it possible to get the file name (and path) from a call to mkstemp()
? And if "yes", how?

- 14,352
- 22
- 97
- 197
2 Answers
From the mkstemp
manual page:
The last six characters of template must be "XXXXXX" and these are replaced with a string that makes the filename unique. Since it will be modified, template must not be a string constant, but should be declared as a character array.
So you declare an array and pass it to the function, which will modify it, and then you have the filename in the array.

- 400,186
- 35
- 402
- 621
-
Right. I didn't think about that. Anyways, what if I pass a const? – alexandernst Sep 08 '15 at 17:04
-
1@alexandernst If you pass a pointer ro a constant or read-only array (like a string literal) you will have undefined behavior. – Some programmer dude Sep 08 '15 at 17:04
-
One last question. Is there an (easy) way to generate templates for different OSes? `tmpnam` seems to do a good job there. – alexandernst Sep 08 '15 at 17:06
-
1@alexandernst: you can build a directory name from `${TMPDIR:-/tmp}` in shell-speak; add some prefix related to your program, and then `.XXXXXX` at the end (so `/tmp/program.XXXXXX` might be OK). If you're really worried, then use `mkdtemp()` to create a unique directory under `${TMPDIR:-/tmp}`, and then create a unique name within that temporary directory. The cleanup is a bit harder; remember `atexit()`. – Jonathan Leffler Sep 08 '15 at 18:48
The input string is modified to the file name. Consequently, it cannot be a string literal.
POSIX says of mkstemp()
:
#include <stdlib.h> int mkstemp(char *template);
The
mkstemp()
function shall replace the contents of the string pointed to bytemplate
by a unique pathname, and return a file descriptor for the file open for reading and writing. … The string intemplate
should look like a pathname with six trailing 'X' s;mkstemp()
replaces each 'X' with a character from the portable filename character set. …
The same page also describes mkdtemp()
which can be used to create a temporary directory.

- 730,956
- 141
- 904
- 1,278