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 the above copyright notice and this paragraph are 7 * duplicated in all such forms and that any documentation, 8 * advertising materials, and other materials related to such 9 * distribution and use acknowledge that the software was developed 10 * by the University of California, Berkeley. The name of the 11 * University may not be used to endorse or promote products derived 12 * from this software without specific prior written permission. 13 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR 14 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED 15 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. 16 */ 17 18 #if defined(LIBC_SCCS) && !defined(lint) 19 static char sccsid[] = "@(#)tempnam.c 4.5 (Berkeley) 06/27/88"; 20 #endif /* LIBC_SCCS and not lint */ 21 22 #include <sys/param.h> 23 #include <sys/stat.h> 24 #include <sys/file.h> 25 #include <stdio.h> 26 27 #define P_tmpdir "/usr/tmp" 28 29 FILE * 30 tmpfile() 31 { 32 FILE *fp; 33 char *f, name[MAXPATHLEN], *tmpnam(); 34 35 if (!(fp = fopen(f = tmpnam(name), "w+"))) { 36 fprintf(stderr, "tmpfile: cannot open %s.\n", name); 37 return(NULL); 38 } 39 (void)unlink(f); 40 return(fp); 41 } 42 43 char * 44 tmpnam(s) 45 char *s; 46 { 47 static char name[MAXPATHLEN]; 48 char *mktemp(); 49 50 if (!s) 51 s = name; 52 (void)sprintf(s, "%s/XXXXXX", P_tmpdir); 53 return(mktemp(s)); 54 } 55 56 char * 57 tempnam(dir, pfx) 58 char *dir, *pfx; 59 { 60 struct stat buf; 61 char *f, *name, *getenv(), *malloc(), *mktemp(), *strcat(), *strcpy(); 62 63 if (!(name = malloc((u_int)MAXPATHLEN))) 64 return(NULL); 65 if ((f = getenv("TMPDIR")) && !stat(f, &buf) && 66 (buf.st_mode&S_IFMT) == S_IFDIR && !access(f, W_OK|X_OK)) { 67 (void)strcpy(name, f); 68 goto done; 69 } 70 if (dir && !stat(dir, &buf) && 71 (buf.st_mode&S_IFMT) == S_IFDIR && !access(dir, W_OK|X_OK)) { 72 (void)strcpy(name, dir); 73 goto done; 74 } 75 if (!stat(P_tmpdir, &buf) && 76 (buf.st_mode&S_IFMT) == S_IFDIR && !access(P_tmpdir, W_OK|X_OK)) { 77 (void)strcpy(name, P_tmpdir); 78 goto done; 79 } 80 if (!stat("/tmp", &buf) && 81 (buf.st_mode&S_IFMT) == S_IFDIR && !access("/tmp", W_OK|X_OK)) { 82 (void)strcpy(name, "/tmp"); 83 goto done; 84 } 85 return(NULL); 86 done: (void)strcat(name, "/"); 87 if (pfx) 88 (void)strcat(name, pfx); 89 (void)strcat(name, "XXXXXX"); 90 return(mktemp(name)); 91 } 92