C++ tmpnam()

The tmpnam() function in C++ generates a unique filename that can be used to create a temporary file without overwriting any existing one.

tmpnam() prototype

char* tmpnam(char* filename);

The tmpnam() function takes a single argument which is a character string and returns a unique filename. This function is capable of generating up to TMP_MAX unique filenames.

It is defined in <cstdio> header file.

tmpnam() Parameters

filename: Pointer to an character array of L_tmpnam bytes, where the proposed temporary name will be stored. If the parameter is a null pointer, the string will be stored in an internal static array.

tmpnam() Return value

  • If filename is not null, it returns filename.
  • If filename is null, a pointer to an internal static buffer is returned.
  • If any error occurs, null is returned.

Example: How tmpnam() function works

#include <iostream>
#include <cstdio>

using namespace std;

int main ()
{
	char filename1[L_tmpnam],filename2[L_tmpnam];
	
	tmpnam(filename1);
	tmpnam(filename2);
	cout << "Temporary filenames:" << endl;
	cout << "1. " << filename1 << endl;
	cout << "2. " << filename2 << endl;

	/*	when null is passed	*/
	char* filename3 = tmpnam(NULL);
	cout << "3. " << filename3; 

  return 0;  
}

When you run the program, the output will be:

Temporary filenames:
1. \s1dg.
2. \s1dg.1
3. \s1dg.2