make fseek detect and produce an error for invalid whence arguments
[musl.git] / src / stdio / tempnam.c
blob565df6b656a957d58694853b982dc1705cac424e
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 #include "kstat.h"
11 #define MAXTRIES 100
13 char *tempnam(const char *dir, const char *pfx)
15 char s[PATH_MAX];
16 size_t l, dl, pl;
17 int try;
18 int r;
20 if (!dir) dir = P_tmpdir;
21 if (!pfx) pfx = "temp";
23 dl = strlen(dir);
24 pl = strlen(pfx);
25 l = dl + 1 + pl + 1 + 6;
27 if (l >= PATH_MAX) {
28 errno = ENAMETOOLONG;
29 return 0;
32 memcpy(s, dir, dl);
33 s[dl] = '/';
34 memcpy(s+dl+1, pfx, pl);
35 s[dl+1+pl] = '_';
36 s[l] = 0;
38 for (try=0; try<MAXTRIES; try++) {
39 __randname(s+l-6);
40 #ifdef SYS_lstat
41 r = __syscall(SYS_lstat, s, &(struct kstat){0});
42 #else
43 r = __syscall(SYS_fstatat, AT_FDCWD, s,
44 &(struct kstat){0}, AT_SYMLINK_NOFOLLOW);
45 #endif
46 if (r == -ENOENT) return strdup(s);
48 return 0;