xref: /original-bsd/lib/libc/stdio/tempnam.c (revision 092d9b4e)
1 /*
2  * Copyright (c) 1988 Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that this notice is preserved and that due credit is given
7  * to the University of California at Berkeley. The name of the University
8  * may not be used to endorse or promote products derived from this
9  * software without specific written prior permission. This software
10  * is provided ``as is'' without express or implied warranty.
11  */
12 
13 #if defined(LIBC_SCCS) && !defined(lint)
14 static char sccsid[] = "@(#)tempnam.c	4.4 (Berkeley) 06/08/88";
15 #endif /* LIBC_SCCS and not lint */
16 
17 #include <sys/param.h>
18 #include <sys/stat.h>
19 #include <sys/file.h>
20 #include <stdio.h>
21 
22 #define	P_tmpdir	"/usr/tmp"
23 
24 FILE *
25 tmpfile()
26 {
27 	FILE *fp;
28 	char *f, name[MAXPATHLEN], *tmpnam();
29 
30 	if (!(fp = fopen(f = tmpnam(name), "w+"))) {
31 		fprintf(stderr, "tmpfile: cannot open %s.\n", name);
32 		return(NULL);
33 	}
34 	(void)unlink(f);
35 	return(fp);
36 }
37 
38 char *
39 tmpnam(s)
40 	char *s;
41 {
42 	static char name[MAXPATHLEN];
43 	char *mktemp();
44 
45 	if (!s)
46 		s = name;
47 	(void)sprintf(s, "%s/XXXXXX", P_tmpdir);
48 	return(mktemp(s));
49 }
50 
51 char *
52 tempnam(dir, pfx)
53 	char *dir, *pfx;
54 {
55 	struct stat buf;
56 	char *f, *name, *getenv(), *malloc(), *mktemp(), *strcat(), *strcpy();
57 
58 	if (!(name = malloc((u_int)MAXPATHLEN)))
59 		return(NULL);
60 	if ((f = getenv("TMPDIR")) && !stat(f, &buf) &&
61 	    (buf.st_mode&S_IFMT) == S_IFDIR && !access(f, W_OK|X_OK)) {
62 		(void)strcpy(name, f);
63 		goto done;
64 	}
65 	if (dir && !stat(dir, &buf) &&
66 	    (buf.st_mode&S_IFMT) == S_IFDIR && !access(dir, W_OK|X_OK)) {
67 		(void)strcpy(name, dir);
68 		goto done;
69 	}
70 	if (!stat(P_tmpdir, &buf) &&
71 	    (buf.st_mode&S_IFMT) == S_IFDIR && !access(P_tmpdir, W_OK|X_OK)) {
72 		(void)strcpy(name, P_tmpdir);
73 		goto done;
74 	}
75 	if (!stat("/tmp", &buf) &&
76 	    (buf.st_mode&S_IFMT) == S_IFDIR && !access("/tmp", W_OK|X_OK)) {
77 		(void)strcpy(name, "/tmp");
78 		goto done;
79 	}
80 	return(NULL);
81 done:	(void)strcat(name, "/");
82 	if (pfx)
83 		(void)strcat(name, pfx);
84 	(void)strcat(name, "XXXXXX");
85 	return(mktemp(name));
86 }
87