What is tmpnam() in C?
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
tmpnamfunction 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
Syntax
The basic syntax of the function is:
Parameters
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.hheader file.
Return Value
The tmpnam function returns a pointer to a C string that contains the valid filename:
-
If the parameter s is a
NULLpointer, the return value will point to thetmpnam'sinternal buffer, which the subsequent calls to the function will overwrite. -
If the parameter s is not
NULL, the function returns s. ANULLpointer is returned in case a suitable filename is not found.
Example
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
tmpnamfunction. Therefore, themkstempfunction is preferred as it creates a file while thetmpnamfunction 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