tempnam() — Generate a temporary file name

Standards

Standards / Extensions C or C++ Dependencies

XPG4
XPG4.2
Single UNIX Specification, Version 3

both

POSIX(ON)

Format

#define _XOPEN_SOURCE
#include <stdio.h>

char *tempnam(const char *dir, const char *pfx);

General description

The tempnam() function generates a path name that may be used for a temporary file. If the environment variable TMPDIR is set, then the directory it specifies will be used as the directory part of the generated path name if it is accessible. Otherwise, if the dir argument is non-NULL and accessible, it will be used in the generated path name. Otherwise, the value of {P_tmpdir} defined in the <stdio.h> header is used as the directory component of the name. If that is inaccessible, then /tmp is used.

The pfx argument can be used to specify an initial component of the file name part of the path name. It may be a NULL pointer or point to a string of up to five bytes to be used as the beginning of a file name.

The names generated are unique across processes and threads, and over time, so multiple threads should be able to each repeatedly call tempnam() and consistently obtain unique names.

This function is supported only in a POSIX program.

Returned value

If successful, tempnam() allocates space for the generated name, copies the name into it, and returns a pointer to the name.

If unsuccessful, tempnam() returns a NULL pointer and sets errno to one of the following values:
Error Code
Description
ENAMETOOLONG
The generated name exceeded the maximum allowable path name length.
ENOMEM
Insufficient storage is available.

Related information