C Library - tmpnam() function

The C library char *tmpnam(char *str) function generates and returns a valid temporary filename which does not exist. If str is null then it simply returns the tmp file name.This function is useful when you need to create a temporary file in a way that minimizes the risk of name conflicts.


Following is the C library syntax of the tmpnam() function −

char *tmpnam(char *str);


This function takes only a single parameter −

  • str: A pointer to an array of at least L_tmpnam characters where the generated temporary file name will be stored. If str is NULL, tmpnam returns a pointer to an internal static buffer that holds the temporary file name.

Return Value

On success, the function returns a pointer to a string containing the generated temporary file name.If str is not NULL, it returns str. If str is NULL, it returns a pointer to an internal static buffer.

Example 1: Using tmpnam with a static buffer

This example shows using tmpnam with NULL to generate a temporary file name and store it in an internal static buffer.

Below is the illustration of the C library tmpnam() function.

#include <stdio.h>

int main() {
   char *filename;

   filename = tmpnam(NULL);
   printf("Generated temporary file name: %s\n", filename);

   return 0;


The above code produces following result−

Generated temporary file name: /tmp/fileXXXXXX

Example 2: Generating multiple temporary file names

This example shows generating multiple temporary file names using separate buffers to ensure each name is stored independently.

#include <stdio.h>

int main() {
   char buffer1[L_tmpnam];
   char buffer2[L_tmpnam];


   printf("Generated temporary file name 1: %s\n", buffer1);
   printf("Generated temporary file name 2: %s\n", buffer2);

   return 0;


After execution of above code, we get the following result −

Generated temporary file name 1: /tmp/fileXXXXXX
Generated temporary file name 2: /tmp/fileYYYYYY