In many cases, the program uses some temporary storage methods in the form of files.
You can use the tmpname function to generate a unique file name.
# Include <stdio. h>
Char * tmpname (char * s)
The tmpname function returns a valid file name that does not have the same name as any existing file name. If String S is not empty, the file name is also written to it. Subsequent call to tmpname
Will overwrite the static storage area that stores the returned values.
If you need to use a temporary file immediately, you can use the tmpfile function to open it while naming it. This is very important. Because another program may create
Tmpfile () completely avoids this situation.
# Include <stdio. h>
File * tmpfile (void );
Tmpfile () returns a file stream pointer pointing to a unique temporary file. This file is opened in read/write mode. When all references to a file are deleted, this temporary file will
Deleted.
If an error occurs, the tmpfile function returns a null pointer and sets the errno value.
#include <stdio.h>#include <stdlib.h>int main(){ char tmpname[L_tmpnam]; char *filename; FILE *tmpfp; filename = tmpnam(tmpname); printf("Temporary file name is: %s\n", filename); tmpfp = tmpfile(); if(tmpfp) printf("Opened a temporary file OK\n"); else perror("tmpfile"); exit(0);}
Another method of generating temporary file names for UNIX is to use the mktemp and mktemp functions.
# Include <stdlib. h>
Char * mktemp (char * template );
Int mkstemp (char * template );
The mktemp function creates a unique file name based on the given template. The template parameter must be a string ending with 6 x characters.
The mkstemp function is similar to tempfile (). It also creates and opens a temporary file. The file name generation method is the same as mktemp, but its return value is
The underlying file descriptor.
In the program, you should use the "Create and open" functions tmpfile and mkstemp instead of tmpname and mktemp functions.