tmpnam()

Generate a unique string for use as a filename

Synopsis:

#include <stdio.h>

char* tmpnam( char* buffer );

Since:

BlackBerry 10.0.0

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:

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

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.

Last modified: 2014-06-24



Got questions about leaving a comment? Get answers from our Disqus FAQ.

comments powered by Disqus