Get the file name that was created by mkstemp()
Asked Answered
N

2

8

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

Nitramine answered 8/9, 2015 at 16:57 Comment(0)
S
12

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.

Shanty answered 8/9, 2015 at 17:2 Comment(4)
Right. I didn't think about that. Anyways, what if I pass a const?Nitramine
@Nitramine If you pass a pointer ro a constant or read-only array (like a string literal) you will have undefined behavior.Shanty
One last question. Is there an (easy) way to generate templates for different OSes? tmpnam seems to do a good job there.Nitramine
@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().Bursarial
B
5

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 by template by a unique pathname, and return a file descriptor for the file open for reading and writing. … The string in template 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.

Bursarial answered 8/9, 2015 at 17:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.