[Previous]
[Contents]
[Next]

tmpnam()

generate a unique string for use as a file name

Synopsis:

#include <stdio.h>
char *tmpnam( char *buffer );

Description:

The tmpnam() function generates a unique string for use as a valid file name.

If the TMPDIR environment variable is defined, its value is used once to initialize a prefix for the temporary file name. If TMPDIR isn't defined, the path /tmp is used as a prefix for the temporary file name. In either case, if the path doesn't exist, the current directory (".") is used. The filename component has the format UUUPPPP.NNNN.TMP, where:

UUU
are unique filename letters for the process (starting with AAA, then AAB, and so on.)
PPPP
is a variable-length string incorporating the process ID (pid), followed by a "."
NNNN
is a variable-length string incorporating the network ID (nid), followed by a "."
TMP
is the suffix TMP

For example, if the process ID is 0x0056 and the network ID is 0x0234 then the first temporary file name produced resembles one of the following:

{TMPDIR_string}/AAAFG.BCD.TMP
           /tmp/AAAFG.BCD.TMP
              ./AAAFG.BCD.TMP

Subsequent calls to tmpnam() reuse the internal buffer. The function generates unique filenames for up to TMP_MAX calls.

Returns:

If the argument buffer is a NULL pointer, tmpnam() returns a pointer to an internal buffer containing the temporary file name. If the argument buffer isn't a NULL pointer, tmpnam() copies the temporary file name from the internal buffer to the specified buffer, and returns a pointer to the specified buffer. It's assumed that the specified buffer is an array of at least L_tmpnam characters.


Note: If the argument buffer is a NULL pointer, you may wish to duplicate the resulting string, since subsequent calls to tmpnam() reuse the internal buffer. For example,

char *name1, *name2;

name1 = strdup( tmpnam( NULL ) );
name2 = strdup( tmpnam( NULL ) );

Examples:

#include <stdio.h>

int main( void )
  {
    char filename[ L_tmpnam ];
    FILE *fp;

    tmpnam( filename );
    fp = fopen( filename, "w" );

    /* ... */

    fclose( fp );
    remove( filename );
    return( EXIT_SUCCESS );
  }

Classification:

ANSI

Safety:
Interrupt handler No
Signal handler No
Thread Yes

See also:

errno, fopen(), freopen(), tmpfile()


[Previous]
[Contents]
[Next]