< cpp‎ | io‎ | c
Revision as of 23:01, 31 May 2013 by P12bot (Talk | contribs)

Defined in header <cstdio>
char* tmpnam( char* filename );

Creates an unique filename that does not name a currently existing file, and stores it in the 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 already be in use, and thus not suitable return values.



filename - pointer to the character array capable of holding at least L_tmpnam bytes, to be used as a result buffer. If NULL is passed, a pointer to an internal static buffer is returned.

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.


When called with null pointer argument, this function modifies a global object. If another thread calls std::tmpnam with null pointer argument at the same time, the behavior is undefined due to a data race.

Although the names generated by std::tmpnam are difficult to guess, it is possible that a file with that name is created by another process between the moment std::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.


#include <iostream>
#include <cstdio>
#include <string>
int main()
    std::string name1 = std::tmpnam(nullptr);
    std::cout << "temporary file name: " << name1 << '\n';
    char name2[L_tmpnam];
        std::cout << "temporary file name: " << name2 << '\n';

Possible output:

temporary file name: /tmp/fileDjwifs
temporary file name: /tmp/fileEv2bfW

See also

creates and opens a temporary, auto-removing file
(function) [edit]
C documentation for tmpnam