What is tmpnam_s() in C?
The tmpnam_s 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_S times. The filenames should not be greater than L_tmpnam_s in length.
TMP_MAX_SandL_tmpnam_sare macros defined in thestdio.hheader file.
To use the tmpnam_s function, we need to include the stdio.h header file, as shown below:
#include stdio.h
Syntax
The tmpnam_s function is declared as follows:
Parameters
The tmpnam_s function takes the following two parameters:
-
A
character pointerthat points to the array of characters. The filename is a C string. -
The maximum number of characters the function is allowed to write. This value is of the
rsize_ttype.
Return value
The tmpnam_s function returns a pointer to a C string that contains the valid filename:
-
If the parameter
filename_sis aNULLpointer, the return value will point to thetmpnam_s'sinternal buffer, which the subsequent calls to the function will overwrite. -
If the parameter
maxsizeis greater thanRSIZE_MAXmacro, an error is generated. -
If the parameter
maxsizeis less than the generated filename string, an error is generated. -
If the parameter
filename_sis notNULL, the function returns the filename. ANULLpointer is returned in case a suitable filename is not found.
Example
The code below shows the use of the tmpnam_s in C. This function works the same way as the tmpnam function in C except for the extra safety checks. First, we call the function, and if an error is detected, we display the error message in line 16. If there are no errors, we display the filename in line 21:
To find more information about the
tmpnamfunction in C, click here.
#include <stdio.h>#include <stdlib.h>int main( void ){//Declare valueschar filename[L_tmpnam_s];errno_t e;//Call the functione = tmpnam_s(filename, L_tmpnam_s );//Display resultif (e){printf("Error occurred! \n");}else{printf( "Temporary filename: %s\n", filename );}}
The filenames generated by the tmpnam_s function are random and difficult to guess.
However, a sample output of the above code is as follows:
Temporary filename: /tmp/fileRZHMwL
Free Resources