xref: /original-bsd/lib/libc/stdio/tempnam.c (revision 82f2451b)
1 /*
2  * Copyright (c) 1988, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)tempnam.c	8.1 (Berkeley) 06/04/93";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <sys/param.h>
13 #include <errno.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <paths.h>
18 
19 char *
tempnam(dir,pfx)20 tempnam(dir, pfx)
21 	const char *dir, *pfx;
22 {
23 	int sverrno;
24 	char *f, *name;
25 
26 	if (!(name = malloc(MAXPATHLEN)))
27 		return(NULL);
28 
29 	if (!pfx)
30 		pfx = "tmp.";
31 
32 	if (f = getenv("TMPDIR")) {
33 		(void)snprintf(name, MAXPATHLEN, "%s%s%sXXXXXX", f,
34 		    *(f + strlen(f) - 1) == '/'? "": "/", pfx);
35 		if (f = mktemp(name))
36 			return(f);
37 	}
38 
39 	if (f = (char *)dir) {
40 		(void)snprintf(name, MAXPATHLEN, "%s%s%sXXXXXX", f,
41 		    *(f + strlen(f) - 1) == '/'? "": "/", pfx);
42 		if (f = mktemp(name))
43 			return(f);
44 	}
45 
46 	f = P_tmpdir;
47 	(void)snprintf(name, MAXPATHLEN, "%s%sXXXXXX", f, pfx);
48 	if (f = mktemp(name))
49 		return(f);
50 
51 	f = _PATH_TMP;
52 	(void)snprintf(name, MAXPATHLEN, "%s%sXXXXXX", f, pfx);
53 	if (f = mktemp(name))
54 		return(f);
55 
56 	sverrno = errno;
57 	free(name);
58 	errno = sverrno;
59 	return(NULL);
60 }
61