#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <trace.h>

/************************************************************************
 *
 * Function:     tmpfile
 *
 * Description:
 *     Create and open a temp file. This file is to be deleted when it
 *     closed.
 *
 *     (Actually, since this is a UNIX system, the file is opened and
 *     then removed. This will leave the name undefined, however, it will
 *     still be open. The file inode will be removed when it is closed.)
 *
 *     The file is opened in "w+" mode. This will allow both read/write
 *     access. Of course, since the file was just opened, doing a read will
 *     result in only EOF.
 *
 * Entry:
 *     none.
 */

#ifdef ELF_LIBRARY
#define tempnam _tempnam
#endif

FILE *tmpfile (void)
    {
    char *pszName;
    FILE *stream = NULL;
    FUNC_ENTRY ("tmpfile");
/*
 *  Generate a temporary file name for the file and try to open the
 *  file.
 */
    pszName = tempnam (NULL, NULL);
    while (pszName != NULL)
        {
	stream = fopen (pszName, "w+");
/*
 *  If the file was created then return.
 */
	if (stream != NULL)
	    {
	    break;
	    }
/*
 *  Access error is the only thing which is allowed at this point.
 */
	if (errno != EACCES)
	    {
	    break;
	    }

	free (pszName);
	pszName = tempnam (NULL, NULL);
        }
/*
 *  If the name was returned then delete the file
 */
    if (stream != NULL)
        {
	unlink (pszName);
        }
/*
 *  If the name was returned then release the temporary buffer
 */
    if (pszName != NULL)
        {
	free (pszName);
        }
/*
 *  Return the file pointer
 */
    FUNC_EXIT ("tmpfile");
    return (stream);
    }
