C in a Nutshell (In a Nutshell (OReilly))

tmpnam

Generates a unique filename

#include <stdio.h> char *tmpnam ( char *s );

The tmpnam( ) function generates a unique filename suitable for using for temporary files, and returns a pointer to the name string. If the pointer argument s is not a null pointer, then tmpnam( ) places the name string in a buffer addressed by s. The size of the buffer is assumed to be at least equal to the macro L_tmpnam. If s is a null pointer, then the return value points to the filename in tmpnam( )'s internal, static buffer, where it may be modified by subsequent tmpnam( ) calls.

If you use a name supplied by tmpnam( ) to create a file, that does not mean the file is a temporary file in the sense of tmpfile( ); it will not be automatically deleted on closing.

The tmpnam( ) function generates a different name each time it is called, and can generate at least TMP_MAX distinct names (some of which may be used by tmpfile( )). The macros L_tmpnam and TMP_MAX are defined in stdio.h. TMP_MAX is greater than or equal to 25. The tmpnam( ) function returns a null pointer on failure.

Example

char buffer[L_tmpnam], *name = buffer; FILE *fpOut; int result; name = tmpnam( buffer ); if ( name == NULL ) { fputs( "Failed to generate temporary file name", stderr ); return -1; } fpOut = fopen( name, "w+" ); /* ... write something in the file, edit it ... */ fclose( fpOut ); printf( "Results saved in %s\n", name );

See Also

tmpfile( ), rename( )

Категории