[ Previous | Next | Contents | Glossary | Home | Search ]
AIX Version 4.3 Base Operating System and Extensions Technical Reference, Volume 1

mktemp or mkstemp Subroutine


Constructs a unique file name.


Standard C Library (libc.a)

Berkeley Compatibility Library (libbsd.a)


#include <stdlib.h>

char *mktemp (Template)
char *Template;
int mkstemp (Template)
char *Template;


The mktemp subroutine replaces the contents of the string pointed to by the Template parameter with a unique file name.

Note: The mktemp subroutine creates a filename and checks to see if the file exist. It that file does not exist, the name is returned. If the user calls mktemp twice without creating a file using the name returned by the first call to mktemp, then the second mktemp call may return the same name as the first mktemp call since the name does not exist.

To avoid this, either create the file after calling mktemp or use the mkstemp subroutine. The mkstemp subroutine creates the file for you.


Template Points to a string to be replaced with a unique file name. The string in the Template parameter is a file name with up to six trailing X's. Since the system randomly generates a six-character string to replace the X's, it is recommended that six trailing X's be used.

Return Values

Upon successful completion, the mktemp subroutine returns the address of the string pointed to by the Template parameter.

If the string pointed to by the Template parameter contains no X's, and if it is an existing file name, the Template parameter is set to a null character, and a null pointer is returned; if the string does not match any existing file name, the exact string is returned.

Upon successful completion, the mkstemp subroutine returns an open file descriptor. If the mkstemp subroutine fails, it returns a value of -1.

Implementation Specifics

These subroutines are part of Base Operating System (BOS) Runtime.

To get the BSD version of this subroutine, compile with Berkeley Compatibility Library (libbsd.a).

The mkstemp subroutine performs the same substitution to the template name and also opens the file for reading and writing.

In BSD systems, the mkstemp subroutine was intended to avoid a race condition between generating a temporary name and creating the file. Because the name generation in the operating system is more random, this race condition is less likely. BSD returns a file name of / (slash).

Former implementations created a unique name by replacing X's with the process ID and a unique letter.

Related Information

The getpid subroutine, tmpfile subroutine, tmpnam or tempnam subroutine.

Files, Directories, and File Systems for Programmers in AIX Version 4.3 General Programming Concepts: Writing and Debugging Programs.

[ Previous | Next | Contents | Glossary | Home | Search ]