Generate a unique string for use as a filename


#include <stdio.h>

char* tmpnam( char* 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.



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


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:

  • If a file with the new name doesn't exist, the new name is returned.
  • If a file with the new name does exist, a default pathname with a basename of 000000 is returned.

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

  • The TMPDIR environment variable
  • The temporary file directory P_tmpdir (defined in <stdio.h>)
  • The _PATH_TMP constant (defined in <paths.h>)

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 ) );


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


#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;


ANSI, POSIX 1003.1

Cancellation point Yes
Interrupt handler No
Signal handler No
Thread Read the 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.