tempnam.c 835 字节
Newer Older
R
Rich Felker 已提交
1
#include <stdio.h>
2 3 4 5
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <limits.h>
R
Rich Felker 已提交
6
#include <string.h>
7
#include "syscall.h"
8 9

#define MAXTRIES 100
R
Rich Felker 已提交
10

11 12
char *__randname(char *);

R
Rich Felker 已提交
13 14
char *tempnam(const char *dir, const char *pfx)
{
15 16 17 18
	char s[PATH_MAX];
	size_t l, dl, pl;
	int try;
	int r;
R
Rich Felker 已提交
19 20 21 22

	if (!dir) dir = P_tmpdir;
	if (!pfx) pfx = "temp";

23 24 25
	dl = strlen(dir);
	pl = strlen(pfx);
	l = dl + 1 + pl + 1 + 6;
R
Rich Felker 已提交
26

27 28
	if (l >= PATH_MAX) {
		errno = ENAMETOOLONG;
29
		return 0;
R
Rich Felker 已提交
30
	}
31 32 33 34 35 36 37 38

	memcpy(s, dir, dl);
	s[dl] = '/';
	memcpy(s+dl+1, pfx, pl);
	s[dl+1+pl] = '_';

	for (try=0; try<MAXTRIES; try++) {
		__randname(s+l-6);
39
#ifdef SYS_lstat
40
		r = __syscall(SYS_lstat, s, &(struct stat){0});
41 42 43 44
#else
		r = __syscall(SYS_fstatat, AT_FDCWD, s,
			&(struct stat){0}, AT_SYMLINK_NOFOLLOW);
#endif
45 46 47
		if (r == -ENOENT) return strdup(s);
	}
	return 0;
R
Rich Felker 已提交
48
}