/* mkstemp.c (emx+gcc) -- Copyright (c) 1995 by Eberhard Mattes */

#include <string.h>
#include <process.h>
#include <io.h>
#include <fcntl.h>
#include <errno.h>

int _mkstemp (char *string)
{
  int fd, pid, n;
  char *s;

  pid = _getpid ();
  s = strchr (string, 0);
  n = 0;
  while (s != string && s[-1] == 'X')
    {
      --s; ++n;
      *s = (char)(pid % 10) + '0';
      pid /= 10;
    }
  if (n < 2)
    {
      errno = EINVAL;
      return -1;
    }
  *s = 'a';
  for (;;)
    {
      fd = _open (string, O_RDWR | O_CREAT | O_EXCL, 0600);
      if (fd >= 0 || errno != EEXIST || *s == 'z')
        return fd;
      ++*s;
    }
}
