mkstemp -- make a unique file name


   cc. . . -lc
   #include <stdlib.h>
   int mkstemp(char *template);


The mkstemp function replaces the contents of the string pointed to by template by a unique file name, and returns a file descriptor for the file open for reading and writing. The function thus prevents any possible race condition between testing whether the file exists and opening it for use.

The string in template should look like a file name with six trailing X characters (XXXXXX); mkstemp replaces each X with a character from the portable file name character set. The characters are chosen such that the resulting name does not duplicate the name of an existing file.

Return values

Upon successful completion, mkstemp returns an open file descriptor. Otherwise -1 is returned if no suitable file could be created.


It is possible to run out of letters.

The mkstemp function does not check to determine whether the file name part of template exceeds the maximum allowable file name length.

mkstemp actually changes the template string which you pass; this means that you cannot use the same template string more than once -- you need a fresh template for every unique file you want to open.

When mkstemp is creating a new unique filename it checks for the prior existence of a file with that name. This means that if you are creating more than one unique filename, it is bad practice to use the same root template for multiple invocations of mkstemp.


For portability with previous versions of the UNIX® system, tmpfile(S) is preferred over this function.

See also

getpid(S), mktemp(S), open(S), tmpfile(S), tmpnam(S)

Standards conformance

This routine conforms to X/Open System Interfaces and Headers, Issue 4, Version 2.
© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003