xref: /csrg-svn/lib/libc/stdio/tempnam.c (revision 58800)
121396Smckusick /*
234684Sbostic  * Copyright (c) 1988 Regents of the University of California.
334684Sbostic  * All rights reserved.
434684Sbostic  *
542635Sbostic  * %sccs.include.redist.c%
621396Smckusick  */
721396Smckusick 
826539Sdonn #if defined(LIBC_SCCS) && !defined(lint)
9*58800Sbostic static char sccsid[] = "@(#)tempnam.c	5.2 (Berkeley) 03/25/93";
1034684Sbostic #endif /* LIBC_SCCS and not lint */
1121396Smckusick 
1234684Sbostic #include <sys/param.h>
1346559Sbostic #include <errno.h>
1434684Sbostic #include <stdio.h>
1546559Sbostic #include <stdlib.h>
1646559Sbostic #include <unistd.h>
1746559Sbostic #include <paths.h>
1834684Sbostic 
1934684Sbostic char *
2046559Sbostic tempnam(dir, pfx)
2146559Sbostic 	const char *dir, *pfx;
2234684Sbostic {
2346559Sbostic 	int sverrno;
2446559Sbostic 	char *f, *name;
2534684Sbostic 
2646559Sbostic 	if (!(name = malloc(MAXPATHLEN)))
2735277Sbostic 		return(NULL);
2834684Sbostic 
2946559Sbostic 	if (!pfx)
3046559Sbostic 		pfx = "tmp.";
3134684Sbostic 
3235277Sbostic 	if (f = getenv("TMPDIR")) {
33*58800Sbostic 		(void)snprintf(name, MAXPATHLEN, "%s%s%sXXXXXX", f,
34*58800Sbostic 		    *(f + strlen(f) - 1) == '/'? "": "/", pfx);
3535277Sbostic 		if (f = mktemp(name))
3635277Sbostic 			return(f);
3734684Sbostic 	}
3846559Sbostic 
3946559Sbostic 	if (f = (char *)dir) {
40*58800Sbostic 		(void)snprintf(name, MAXPATHLEN, "%s%s%sXXXXXX", f,
41*58800Sbostic 		    *(f + strlen(f) - 1) == '/'? "": "/", pfx);
4235277Sbostic 		if (f = mktemp(name))
4335277Sbostic 			return(f);
4434684Sbostic 	}
4546559Sbostic 
4646559Sbostic 	f = P_tmpdir;
47*58800Sbostic 	(void)snprintf(name, MAXPATHLEN, "%s%sXXXXXX", f, pfx);
4835277Sbostic 	if (f = mktemp(name))
4935277Sbostic 		return(f);
5046559Sbostic 
5146559Sbostic 	f = _PATH_TMP;
52*58800Sbostic 	(void)snprintf(name, MAXPATHLEN, "%s%sXXXXXX", f, pfx);
5346559Sbostic 	if (f = mktemp(name))
5446559Sbostic 		return(f);
5546559Sbostic 
5646559Sbostic 	sverrno = errno;
5746559Sbostic 	free(name);
5846559Sbostic 	errno = sverrno;
5946559Sbostic 	return(NULL);
6034684Sbostic }
61