1#include <errno.h> 2#include <fcntl.h> 3#include <limits.h> 4#include <stdio.h> 5#include <string.h> 6#include <sys/stat.h> 7 8#define MAXTRIES 100 9 10char* __randname(char*); 11 12char* tempnam(const char* dir, const char* pfx) { 13 char s[PATH_MAX]; 14 size_t l, dl, pl; 15 int try 16 ; 17 int r; 18 19 if (!dir) 20 dir = P_tmpdir; 21 if (!pfx) 22 pfx = "temp"; 23 24 dl = strlen(dir); 25 pl = strlen(pfx); 26 l = dl + 1 + pl + 1 + 6; 27 28 if (l >= PATH_MAX) { 29 errno = ENAMETOOLONG; 30 return 0; 31 } 32 33 memcpy(s, dir, dl); 34 s[dl] = '/'; 35 memcpy(s + dl + 1, pfx, pl); 36 s[dl + 1 + pl] = '_'; 37 s[l] = 0; 38 39 for (try = 0; try < MAXTRIES; try ++) { 40 __randname(s + l - 6); 41 r = lstat(s, &(struct stat){}); 42 if (r == -1 && errno == ENOENT) { 43 return strdup(s); 44 } 45 } 46 return 0; 47} 48