xref: /titanic_41/usr/src/lib/libbc/libc/stdio/common/tempnam.c (revision 1ae0874509b6811fdde1dfd46f0d93fd09867a3f)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 1993 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*      Copyright (c) 1984 AT&T */
28 /*        All Rights Reserved   */
29 
30 #pragma ident	"%Z%%M%	%I%	%E% SMI"  /* from S5R2 1.1 */
31 
32 /*LINTLIBRARY*/
33 #include <stdio.h>
34 #include <string.h>
35 
36 #define max(A,B) (((A)<(B))?(B):(A))
37 
38 extern char *malloc(), *getenv(), *mktemp();
39 extern int access();
40 
41 static char *pcopy();
42 static char seed[4];
43 
44 char *
45 tempnam(dir, pfx)
46 char *dir;		/* use this directory please (if non-NULL) */
47 char *pfx;		/* use this (if non-NULL) as filename prefix */
48 {
49 	register char *p, *q, *tdir;
50 	int x=0, y=0, z;
51 
52 	if (seed[0] == 0)
53 		seed[0] = seed[1] = seed[2] = 'A';
54 	z=strlen(P_tmpdir);
55 	if((tdir = getenv("TMPDIR")) != NULL) {
56 		x = strlen(tdir);
57 	}
58 	if(dir != NULL) {
59 		y=strlen(dir);
60 	}
61 	if((p=malloc((unsigned)(max(max(x,y),z)+16))) == NULL)
62 		return(NULL);
63 	if(x > 0 && access(pcopy(p, tdir), 3) == 0)
64 		goto OK;
65 	if(y > 0 && access(pcopy(p, dir), 3) == 0)
66 		goto OK;
67 	if(access(pcopy(p, P_tmpdir), 3) == 0)
68 		goto OK;
69 	if(access(pcopy(p, "/tmp"), 3) != 0)
70 		return(NULL);
71 OK:
72 	(void)strcat(p, "/");
73 	if(pfx) {
74 		*(p+strlen(p)+5) = '\0';
75 		(void)strncat(p, pfx, 5);
76 	}
77 	(void)strcat(p, seed);
78 	(void)strcat(p, "XXXXXX");
79 	q = seed;
80 	while(*q == 'Z')
81 		*q++ = 'A';
82 	++*q;
83 	if(*mktemp(p) == '\0')
84 		return(NULL);
85 	return(p);
86 }
87 
88 static char*
89 pcopy(space, arg)
90 char *space, *arg;
91 {
92 	char *p;
93 
94 	if(arg) {
95 		(void)strcpy(space, arg);
96 		p = space-1+strlen(space);
97 		if(*p == '/')
98 			*p = '\0';
99 	}
100 	return(space);
101 }
102