mktemp.c 539 B

1234567891011121314151617181920212223242526272829303132
  1. #define _GNU_SOURCE
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <errno.h>
  5. #include <sys/stat.h>
  6. char *__randname(char *);
  7. char *mktemp(char *template)
  8. {
  9. size_t l = strlen(template);
  10. int retries = 100;
  11. struct stat st;
  12. if (l < 6 || memcmp(template+l-6, "XXXXXX", 6)) {
  13. errno = EINVAL;
  14. *template = 0;
  15. return template;
  16. }
  17. do {
  18. __randname(template+l-6);
  19. if (stat(template, &st)) {
  20. if (errno != ENOENT) *template = 0;
  21. return template;
  22. }
  23. } while (--retries);
  24. *template = 0;
  25. errno = EEXIST;
  26. return template;
  27. }