update for HEAD-2003091401
[reactos.git] / lib / crtdll / stdio / tmpfile.c
1 /* Copyright (C) 1998 DJ Delorie, see COPYING.DJ for details */
2 /* Copyright (C) 1997 DJ Delorie, see COPYING.DJ for details */
3 /* Copyright (C) 1998 DJ Delorie, see COPYING.DJ for details */
4 /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
5
6 #include <msvcrt/stdio.h>
7 #include <msvcrt/string.h>
8 #include <msvcrt/stdlib.h>
9 #include <msvcrt/errno.h>
10 #include <msvcrt/fcntl.h>
11 //#include <msvcrt/unistd.h>
12 #include <msvcrt/io.h>
13 #include <msvcrt/share.h>
14 #include <msvcrt/internal/file.h>
15
16
17 FILE *  __alloc_file(void);
18
19 /*
20  * @implemented
21  */
22 FILE *
23 tmpfile(void)
24 {
25   int  temp_fd;
26   FILE *f;
27   char *temp_name = tmpnam(0);
28   char *n_t_r = (char *)malloc(L_tmpnam);
29
30   if (!n_t_r)
31     return 0;
32
33   /* We could have a race condition, whereby another program
34      (in another virtual machine, or if the temporary file is
35      in a directory which is shared via a network) opens the
36      file returned by `tmpnam' between the call above and the
37      moment when we actually open the file below.  This loop
38      retries the call to `tmpnam' until we actually succeed
39      to create the file which didn't exist before.  */
40   do {
41    // errno = 0;
42     temp_fd = _open(temp_name, 0, SH_DENYRW);
43   //  if (  errno == ENOENT )
44 //      break;
45   } while (temp_fd == -1 && (temp_name = tmpnam(0)) != 0);
46
47   if (temp_name == 0)
48     return 0;
49
50   /* This should have been fdopen(temp_fd, "wb+"), but `fdopen'
51      is non-ANSI.  So we need to dump some of its guts here.  Sigh...  */
52   f = __alloc_file();
53   if (f)
54   {
55     f->_file   = temp_fd;
56     f->_cnt    = 0;
57     f->_bufsiz = 0;
58     f->_flag   = _IORMONCL | _IOREAD | _IOWRT;
59     f->_name_to_remove = n_t_r;
60     strcpy(f->_name_to_remove, temp_name);
61     f->_base = f->_ptr = NULL;
62   }
63   else
64   {
65     close(temp_fd);
66     remove(temp_name);
67     free(n_t_r);
68   }
69   return f;
70 }