mkstemp.c 614 B

12345678910111213141516171819202122232425262728
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <fcntl.h>
  5. #include <unistd.h>
  6. #include <limits.h>
  7. #include <errno.h>
  8. #include "libc.h"
  9. char *__mktemp(char *);
  10. int mkstemp(char *template)
  11. {
  12. int fd, retries = 100, t0 = *template;
  13. while (retries--) {
  14. if (!*__mktemp(template)) return -1;
  15. if ((fd = open(template, O_RDWR | O_CREAT | O_EXCL, 0600))>=0)
  16. return fd;
  17. if (errno != EEXIST) return -1;
  18. /* this is safe because mktemp verified
  19. * that we have a valid template string */
  20. template[0] = t0;
  21. strcpy(template+strlen(template)-6, "XXXXXX");
  22. }
  23. return -1;
  24. }
  25. LFS64(mkstemp);