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