Many applications create temporary files that should be deleted after
the process terminates. For example, a Web browser caches pages that
have been viewed during the current browsing session in temporary files,
while some applications use per-session log files. The snag is that most
programs don't delete these temporary files when they terminate.
Instead, they store them in a special directory that you have to expunge
manually every once in awhile. Most programmers aren't aware of two
functions that automate most of this drudgery.
Generating Unique Filenames
If you only need to generate unique filenames, then use the standard
function tmpnam(). tmpnam() is declared in <stdio.h> as follows:
char * tmpnam(char * name);
The argument 'name' contains a pointer to a buffer that has at least
L_tmpnam characters. If you pass a NULL pointer as an argument, then
tmpnam() stores the generated filename in an internal static buffer and
returns its address. Remember to copy the returned filename to another
buffer before calling tmpnam() once more, as each call overwrites the
previous filename. tmpnam() returns a filename that doesn't conflict
with any other file in the current directory. You can call tmpnam() up
to TMP_MAX (the TMP_MAX and L_tmpnam constants are defined in
<stdlib.h>) times without generating repeated names. The following
program calls tmpnam() 10 times and prints the generated names:
#include <stdio.h>
int main()
{
char name[L_tmpnam];
for (int n=0; n<10; ++n)
{
tmpnam(name);
printf("%s", name);
}
}
Generating Temporary Files
tmpnam() only generates unique filenames; it doesn't free you from
manually opening those files and deleting them afterwards. The tmpfile()
function, on the other hand, does all of that for you. The tmpfile()
function is declared in <stdio.h> as follows:
FILE * tmpfile();
This function opens a temporary file for read/write operations and
returns a FILE* associated with that file. tmpfile()avoids conflicts
with any existing files by using tmpnam() internally. Files created by
tmpfile() are automatically deleted when the program terminates, thus
you don't have to manually delete them.