mkstemp.c 630 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #include <string.h>
  2. #include <features.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. int mkstemp(template)
  6. char *template;
  7. {
  8. int i;
  9. int num __attribute__ ((unused)); /* UNINITIALIZED */
  10. int n2;
  11. int l = strlen(template);
  12. if (l < 6) {
  13. errno = EINVAL;
  14. return -1;
  15. }
  16. for (i = l - 6; i < l; i++)
  17. if (template[i] != 'X') {
  18. errno = EINVAL;
  19. return -1;
  20. }
  21. again:
  22. n2 = num;
  23. for (i = l - 1; i >= l - 6; i--) {
  24. template[i] = '0' + n2 % 10;
  25. n2 /= 10;
  26. }
  27. i = open(template, O_RDWR | O_EXCL | O_CREAT, 0666);
  28. if (i == -1) {
  29. if (errno == EEXIST) {
  30. num++;
  31. goto again;
  32. } else
  33. return -1;
  34. }
  35. return i;
  36. }