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_S
andL_tmpnam_s
are macros defined in thestdio.h
header file.
To use the tmpnam_s
function, we need to include the stdio.h
header file, as shown below:
#include stdio.h
The tmpnam_s
function is declared as follows:
The tmpnam_s
function takes the following two parameters:
A character pointer
that 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_t
type.
The tmpnam_s
function returns a pointer to a C string that contains the valid filename:
If the parameter filename_s
is a NULL
pointer, the return value will point to the tmpnam_s's
internal buffer, which the subsequent calls to the function will overwrite.
If the parameter maxsize
is greater thanRSIZE_MAX
macro, an error is generated.
If the parameter maxsize
is less than the generated filename string, an error is generated.
If the parameter filename_s
is not NULL
, the function returns the filename. A NULL
pointer is returned in case a suitable filename is not found.
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
tmpnam
function 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