Creates a unique filename.
#include <io.h> | Required only for function declarations |
char *_mktemp( char *template );
template | Filename pattern |
The _mktemp function creates a unique filename by modifying the given template argument. The template argument has the form:
baseXXXXXX
where base is the part of the new filename that you supply, and the X's are placeholders for the part supplied by _mktemp; _mktemp preserves base and replaces the six trailing X's with an alphanumeric character followed by a five-digit value. The five-digit value is a unique number identifying the calling process. The alphanumeric character is 0 ('0') the first time _mktemp is called with a given template.
In subsequent calls from the same process with copies of the same template, _mktemp checks to see if previously returned names have been used to create files. If no file exists for a given name, _mktemp returns that name. If files exist for all previously returned names, _mktemp creates a new name by replacing the alphanumeric character in the name with the next available lowercase letter. For example, if the first name returned is t012345 and this name is used to create a file, the next name returned will be ta12345. When creating new names, _mktemp uses, in order, '0' and then the lowercase letters 'a' through 'z'.
Note that the original template is modified by the first call to _mktemp. If you then call the _mktemp function again with the same template (i.e., the original one), you will get an error.
The _mktemp function generates unique filenames but does not create or open files.
The _mktemp function returns a pointer to the modified template. The return value is NULL if the template argument is badly formed or no more unique names can be created from the given template.
Standards:UNIX
16-Bit:DOS, QWIN, WIN, WIN DLL
32-Bit:DOS32X
Use _mktemp for compatibility with ANSI naming conventions of non-ANSI functions. Use mktemp and link with OLDNAMES.LIB for UNIX compatibility.
fopen, _getpid, _open, _tempnam, tmpfile
/* MKTEMP.C: The program uses _mktemp to create five unique filenames.
* It opens each filename to ensure that the next name is unique.
*/
#include <io.h>
#include <string.h>
#include <stdio.h>
char *template = "fnXXXXXX";
char *result;
char names[5][9];
void main( void )
{
int i;
FILE *fp;
for( i = 0; i < 5; i++ )
{
strcpy( names[i], template );
/* Attempt to find a unique filename: */
result = _mktemp( names[i] );
if( result == NULL )
printf( "Problem creating the template" );
else
{
if( (fp = fopen( result, "w" )) != NULL )
printf( "Unique filename is %s\n", result );
else
printf( "Cannot open %s\n", result );
fclose( fp );
}
}
}
Unique filename is fn000686
Unique filename is fna00686
Unique filename is fnb00686
Unique filename is fnc00686
Unique filename is fnd00686