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 tmpnam function can create. It is greater than or equal to 25.

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 the stdio.h header file.

Return Value

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.

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 tmpnam function. Therefore, the mkstemp function is preferred as it creates a file while the tmpnam function only returns the filename.

#include <stdio.h>
int main() {
//Define the array of characters and its size
char arr[L_tmpnam + 1];
char *s;
//Call the tmpnam fucntion
s = tmpnam(arr);
printf ("The temporary filename is: %s\n", s);
//Call the tmpnam function
s = tmpnam(NULL);
printf ("The temporary filename is: %s\n", s);
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved