update for HEAD-2003091401
[reactos.git] / lib / msvcrt / io / mktemp.c
1 /*
2  * COPYRIGHT:   See COPYING in the top level directory
3  *      Copyright (C) 1994 DJ Delorie, see COPYING.DJ for details 
4  * PROJECT:     ReactOS system libraries
5  * FILE:        lib/msvcrt/io/mktemp.c
6  * PURPOSE:     Makes a temp file based on a template
7  * PROGRAMER:   DJ Delorie
8                 Boudewijn Dekker
9  * UPDATE HISTORY:
10  *              28/12/98: Appropriated for the Reactos Kernel
11  */
12
13 /* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
14 /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
15
16 #include <msvcrt/stdio.h>
17 #include <msvcrt/string.h>
18 #include <msvcrt/io.h>
19
20 #define NDEBUG
21 #include <msvcrt/msvcrtdbg.h>
22
23
24 /*
25  * @implemented
26  */
27 char* _mktemp(char* _template)
28 {
29   static int count = 0;
30   char *cp, *dp;
31   int i, len, xcount, loopcnt;
32
33   DPRINT("_mktemp('%s')\n", _template);
34   len = strlen (_template);
35   cp = _template + len;
36
37   xcount = 0;
38   while (xcount < 6 && cp > _template && cp[-1] == 'X')
39     xcount++, cp--;
40
41   if (xcount) {
42     dp = cp;
43     while (dp > _template && dp[-1] != '/' && dp[-1] != '\\' && dp[-1] != ':')
44       dp--;
45
46     /* Keep the first characters of the template, but turn the rest into
47        Xs.  */
48     while (cp > dp + 8 - xcount) {
49       *--cp = 'X';
50       xcount = (xcount >= 6) ? 6 : 1 + xcount;
51     }
52
53     /* If dots occur too early -- squash them.  */
54     while (dp < cp) {
55       if (*dp == '.') *dp = 'a';
56       dp++;
57     }
58
59     /* Try to add ".tmp" to the filename.  Truncate unused Xs.  */
60     if (cp + xcount + 3 < _template + len)
61       strcpy (cp + xcount, ".tmp");
62     else
63       cp[xcount] = 0;
64
65     /* This loop can run up to 2<<(5*6) times, or about 10^9 times.  */
66     for (loopcnt = 0; loopcnt < (1 << (5 * xcount)); loopcnt++) {
67       int c = count++;
68       for (i = 0; i < xcount; i++, c >>= 5)
69     cp[i] = "abcdefghijklmnopqrstuvwxyz012345"[c & 0x1f];
70       if (_access(_template,0) == -1)
71     return _template;
72     }
73   }
74
75   /* Failure:  truncate the template and return NULL.  */
76   *_template = 0;
77   return 0;
78 }