Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is tmpnam() in C?

Umme Ammara

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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;
}

RELATED TAGS

c

CONTRIBUTOR

Umme Ammara
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring