Caution: This version of this document is no longer maintained. For the latest documentation, see http://www.qnx.com/developers/docs.

tmpnam()

Generate a unique string for use as a filename

Synopsis:

#include <stdio.h>

char* tmpnam( char* buffer );

Arguments:

buffer
NULL, or a pointer to a buffer where the function can store the filename. If buffer isn't NULL, the buffer must be at least L_tmpnam bytes long.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The tmpnam() function generates a unique string that's a valid filename and that's not the same as the name of an existing file.

The tmpnam() function generates up to TMP_MAX unique file names before it starts to recycle them.

The generated filename is prefixed with the first accessible directory contained in:

If all of these paths are inaccessible, tmpnam() attempts to use /tmp and then the current working directory.

The generated filename is stored in an internal buffer; if buffer is NULL, the function returns a pointer to this buffer; otherwise, tmpnam() copies the filename into buffer.

Subsequent calls to tmpnam() reuse the internal buffer. If buffer is NULL, you might want to duplicate the resulting string. For example,

char *name1, *name2;

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

Returns:

A pointer to the generated filename for success, or NULL if an error occurs (errno is set).

Examples:

#include <stdio.h>
#include <stdlib.h>

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

    tmpnam( filename );
    fp = fopen( filename, "w+b" );
…
    fclose( fp );
    remove( filename );
    
    return EXIT_SUCCESS;
}

Classification:

ANSI, POSIX 1003.1

Safety:
Cancellation point Yes
Interrupt handler No
Signal handler No
Thread Read the Caveats

Caveats:

The tmpnam() function isn't thread-safe if you pass it a NULL buffer.

This function only creates pathnames; the application must create and remove the files.

It's possible for another thread or process to create a file with the same name between when the pathname is created and the file is opened.

See also:

tempnam(), tmpfile()