Note the usage of temporary files: files cannot be edited by multiple tasks at the same time.
Char * tmpnam (char * s) creates a file with different names from all existing files.
Problem: other programs can also open and edit files with the same name as the names returned by tmpnam.
Note: The file name is assumed to at least l_tmpnam (usually 20) characters long
This function can be called at least several thousand times in a single program.
File * tmpfile (void); this prevents the Same Name of the above file because it is created to open the file at the same time
The returned stream Pointer Points to a unique temporary file and opens the file when it is created. The file mode is readable and writable, and
Will be automatically deleted when all references to the file are closed.
Code:
# 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 );
}
Output:
Temporary File Name is:/tmp/filesua8ul
Opened a temporary file OK
The unix version provides the same functionality as tmpnam, Except t that you can specify
Template for the temporary file name, which gives you a little more control over
File Location and name
# Include <stdlib. h>
Char * mktemp (char * template );
Int mkstemp (char * template );
Conclusion: You should always use the "Create and open" function, such as tmpfile and mkstemp,
Rather than tmpnam and mktemp functions.