tmpnam, tmpnam_s

Header: <stdio.h>

  1. Creates a unique valid file name (no longer than L_tmpnam in length) and stores it in character string pointed to by filename. The function is capable of generating up to TMP_MAX of unique filenames, but some or all of them may be in use in the filesystem and thus not suitable return values.

# Declarations

char *tmpnam( char *filename );
errno_t tmpnam_s(char *filename_s, rsize_t maxsize);

(since C11)

#define TMP_MAX /*unspecified*/
#define TMP_MAX_S /*unspecified*/

(since C11)

#define L_tmpnam /*unspecified*/
#define L_tmpnam_s /*unspecified*/

(since C11)

# Parameters

# Notes

Although the names generated by tmpnam are difficult to guess, it is possible that a file with that name is created by another process between the moment tmpnam returns and the moment this program attempts to use the returned name to create a file. The standard function tmpfile and the POSIX function mkstemp do not have this problem (creating a unique directory using only the standard C library still requires the use of tmpnam).

POSIX systems additionally define the similarly named function tempnam, which offers the choice of a directory (which defaults to the optionally defined macro P_tmpdir).

# Example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main(void)
{
    // Note, the compiler/linker may issue a security warning, e.g. GCC:
    // "warning: the use of `tmpnam' is dangerous, better use `mkstemp'"
    char* name1 = tmpnam(NULL);
    printf("temporary file name: %s\n", name1);
 
    char name2[L_tmpnam];
    if (tmpnam(name2))
        printf("temporary file name: %s\n", name2);
 
    // POSIX offers mkstemp. The following declaration might be
    // necessary as mkstemp is absent in the standard C <stdlib.h>.
    int mkstemp(char*);
 
    char name3[] = "/tmp/fileXXXXXX"; // at least six 'X' required ^_^
    int file_descriptor = mkstemp(name3);
    if (file_descriptor != -1)
        printf("temporary file name: %s\n", name3);
    else
        perror("mkstemp");
}

# See also