The tmpnam
function is a C library function that creates a unique name for temporary files. The function generates a different filename each time we call the function, up to TMP_MAX
times.
TMP_MAX is the maximum number of filenames that the
tmpnam
function can create. It is greater than or equal to25
.
The tmpnam
function and TMP_MAX
are declared in the stdio.h
header file as shown below:
#include stdio.h
The basic syntax of the function is:
The tmpnam
function takes a single char pointer
which points to the array of characters. The filename is a C string.
The size of the array of characters is at least equal to
L_tmpnam
, defined in thestdio.h
header file.
The tmpnam
function returns a pointer to a C string that contains the valid filename:
If the parameter s is a NULL
pointer, the return value will point to the tmpnam's
internal buffer, which the subsequent calls to the function will overwrite.
If the parameter s is not NULL
, the function returns s. A NULL
pointer is returned in case a suitable filename is not found.
The following code example shows the generation of a temporary filename stored in the array of characters. The tmpnam
function returns a different filename when it is called the second time in line 14
, as we see below:
The warning generated in the code below indicates that there is a possibility of two files having the same name while using the
tmpnam
function. Therefore, themkstemp
function is preferred as it creates a file while thetmpnam
function only returns the filename.
#include <stdio.h>int main() {//Define the array of characters and its sizechar arr[L_tmpnam + 1];char *s;//Call the tmpnam fucntions = tmpnam(arr);printf ("The temporary filename is: %s\n", s);//Call the tmpnam functions = tmpnam(NULL);printf ("The temporary filename is: %s\n", s);return 0;}
Free Resources