tempnam.c 860 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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"
  10. #define MAXTRIES 100
  11. char *tempnam(const char *dir, const char *pfx)
  12. {
  13. char s[PATH_MAX];
  14. size_t l, dl, pl;
  15. int try;
  16. int r;
  17. if (!dir) dir = P_tmpdir;
  18. if (!pfx) pfx = "temp";
  19. dl = strlen(dir);
  20. pl = strlen(pfx);
  21. l = dl + 1 + pl + 1 + 6;
  22. if (l >= PATH_MAX) {
  23. errno = ENAMETOOLONG;
  24. return 0;
  25. }
  26. memcpy(s, dir, dl);
  27. s[dl] = '/';
  28. memcpy(s+dl+1, pfx, pl);
  29. s[dl+1+pl] = '_';
  30. s[l] = 0;
  31. for (try=0; try<MAXTRIES; try++) {
  32. __randname(s+l-6);
  33. #ifdef SYS_lstat
  34. r = __syscall(SYS_lstat, s, &(struct kstat){0});
  35. #else
  36. r = __syscall(SYS_fstatat, AT_FDCWD, s,
  37. &(struct kstat){0}, AT_SYMLINK_NOFOLLOW);
  38. #endif
  39. if (r == -ENOENT) return strdup(s);
  40. }
  41. return 0;
  42. }