##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# tmpnam

From cppreference.com
< c‎ | io

Defined in header `<stdio.h>` |  |
char *tmpnam( char *filename ); |  |

Creates an unique filename and stores it in character string pointed to by `filename`. The function is capable of generating up to TMP_MAX of unique filenames, but some or all of them may be in use in the filesystem and thus not suitable return values.

`tmpnam` is not reentrant and thus not thread-safe.

### [edit] Parameters

filename | - | pointer to the character string to be used as a result buffer. If `NULL` is passed, a pointer to an internal static buffer is returned.

### [edit] Return value

`filename` if `filename` was not NULL. Otherwise a pointer to an internal static buffer is returned. If no suitable filename can be generated, NULL is returned.

### [edit] Notes

Although the names generated by `tmpnam` are difficult to guess, it is possible that a file with that name is created by another process between the moment `tmpnam` returns and the moment this program attempts to use the returned name to create a file. The standard function std::tmpfile and the POSIX function mkstemp do not have this problem.

POSIX systems additionally define the similarly named function `tempnam()`, which offers the choice of a directory (which defaults to the optionally defined macro `P_tmpdir)`

### [edit] Example

tmpnam with error checking. Code generates a unique filename.

Run this code

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

    int main(void)
    {
        printf("TMP_MAX  = %d\n", TMP_MAX);
        printf("L_tmpnam = %d\n", L_tmpnam);
        char buffer[L_tmpnam] = {'\0'};
        char * fname = tmpnam(buffer);
        if (fname == NULL)
        {
          perror("tmpnam()");
          fprintf(stderr,"tmpnam() failed in file %s at line # %d\n", __FILE__,__LINE__-4);
          exit(EXIT_FAILURE);
        }
        printf("%s\n", fname);
        printf("%s\n", buffer);
        printf("\n");

        /* Argument is a null pointer. */
        char * fn1 = tmpnam(NULL);
        printf("%s\n", fn1);
        printf("%p\n", fn1);
        /* Subsequent calls to tmpnam modify the same object. */
        char * fn2 = tmpnam(NULL);
        printf("%s\n", fn2);
        printf("%p\n", fn2);

        exit(EXIT_SUCCESS);
    }

Output:

    TMP_MAX  = 238328
    L_tmpnam = 20
    /tmp/filer8fER3
    /tmp/filer8fER3

    /tmp/fileurN5sQ
    0x7f0f05dc7a10
    /tmp/file1Pux4C
    0x7f0f05dc7a10

### [edit] See also

tmpfile | returns a pointer to a temporary file (function) [edit]
C++ documentation for tmpnam

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=c/io/tmpnam&oldid=69944"