Support for nonstandard baud rate in SetCommState.
[wine] / dlls / msvcrt / file.c
1 /*
2  * msvcrt.dll file functions
3  *
4  * Copyright 1996,1998 Marcus Meissner
5  * Copyright 1996 Jukka Iivonen
6  * Copyright 1997,2000 Uwe Bonnes
7  * Copyright 2000 Jon Griffiths
8  */
9 #include <time.h>
10 #include <stdio.h>
11 #include <unistd.h>
12
13 #include "ntddk.h"
14 #include "msvcrt.h"
15 #include "ms_errno.h"
16
17 #include "wine/unicode.h"
18 #include "msvcrt/direct.h"
19 #include "msvcrt/fcntl.h"
20 #include "msvcrt/io.h"
21 #include "msvcrt/stdio.h"
22 #include "msvcrt/stdlib.h"
23 #include "msvcrt/string.h"
24 #include "msvcrt/sys/stat.h"
25 #include "msvcrt/sys/utime.h"
26 #include "msvcrt/time.h"
27
28 #include "wine/debug.h"
29
30 WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
31
32 /* for stat mode, permissions apply to all,owner and group */
33 #define MSVCRT_S_IREAD  (_S_IREAD  | (_S_IREAD  >> 3) | (_S_IREAD  >> 6))
34 #define MSVCRT_S_IWRITE (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6))
35 #define MSVCRT_S_IEXEC  (_S_IEXEC  | (_S_IEXEC  >> 3) | (_S_IEXEC  >> 6))
36
37 /* _access() bit flags FIXME: incomplete */
38 #define MSVCRT_W_OK      0x02
39
40
41 /* FIXME: Make this dynamic */
42 #define MSVCRT_MAX_FILES 257
43
44 HANDLE MSVCRT_handles[MSVCRT_MAX_FILES];
45 MSVCRT_FILE* MSVCRT_files[MSVCRT_MAX_FILES];
46 int  MSVCRT_flags[MSVCRT_MAX_FILES];
47 char *MSVCRT_tempfiles[MSVCRT_MAX_FILES];
48 MSVCRT_FILE MSVCRT__iob[3];
49 #define MSVCRT_stdin       (MSVCRT__iob+STDIN_FILENO)
50 #define MSVCRT_stdout      (MSVCRT__iob+STDOUT_FILENO)
51 #define MSVCRT_stderr      (MSVCRT__iob+STDERR_FILENO)
52
53 static int MSVCRT_fdstart = 3; /* first unallocated fd */
54 static int MSVCRT_fdend = 3; /* highest allocated fd */
55
56 /* INTERNAL: process umask */
57 static int MSVCRT_umask = 0;
58
59 /* INTERNAL: Static buffer for temp file name */
60 static char MSVCRT_tmpname[MAX_PATH];
61
62 static const unsigned int EXE = 'e' << 16 | 'x' << 8 | 'e';
63 static const unsigned int BAT = 'b' << 16 | 'a' << 8 | 't';
64 static const unsigned int CMD = 'c' << 16 | 'm' << 8 | 'd';
65 static const unsigned int COM = 'c' << 16 | 'o' << 8 | 'm';
66
67 #define TOUL(x) (ULONGLONG)((WCHAR)L##x)
68 static const ULONGLONG WCEXE = TOUL('e') << 32 | TOUL('x') << 16 | TOUL('e');
69 static const ULONGLONG WCBAT = TOUL('b') << 32 | TOUL('a') << 16 | TOUL('t');
70 static const ULONGLONG WCCMD = TOUL('c') << 32 | TOUL('m') << 16 | TOUL('d');
71 static const ULONGLONG WCCOM = TOUL('c') << 32 | TOUL('o') << 16 | TOUL('m');
72
73 extern CRITICAL_SECTION MSVCRT_file_cs;
74 #define LOCK_FILES     EnterCriticalSection(&MSVCRT_file_cs)
75 #define UNLOCK_FILES   LeaveCriticalSection(&MSVCRT_file_cs)
76
77
78 /* INTERNAL: Get the HANDLE for a fd */
79 static HANDLE msvcrt_fdtoh(int fd)
80 {
81   if (fd < 0 || fd >= MSVCRT_fdend ||
82       MSVCRT_handles[fd] == INVALID_HANDLE_VALUE)
83   {
84     WARN(":fd (%d) - no handle!\n",fd);
85     SET_THREAD_VAR(doserrno,0);
86     SET_THREAD_VAR(errno,MSVCRT_EBADF);
87    return INVALID_HANDLE_VALUE;
88   }
89   return MSVCRT_handles[fd];
90 }
91
92 /* INTERNAL: free a file entry fd */
93 static void msvcrt_free_fd(int fd)
94 {
95   MSVCRT_handles[fd] = INVALID_HANDLE_VALUE;
96   MSVCRT_files[fd] = 0;
97   MSVCRT_flags[fd] = 0;
98   TRACE(":fd (%d) freed\n",fd);
99   if (fd < 3)
100     return; /* dont use 0,1,2 for user files */
101   if (fd == MSVCRT_fdend - 1)
102     MSVCRT_fdend--;
103   if (fd < MSVCRT_fdstart)
104     MSVCRT_fdstart = fd;
105 }
106
107 /* INTERNAL: Allocate an fd slot from a Win32 HANDLE */
108 static int msvcrt_alloc_fd(HANDLE hand, int flag)
109 {
110   int fd = MSVCRT_fdstart;
111
112   TRACE(":handle (%d) allocating fd (%d)\n",hand,fd);
113   if (fd >= MSVCRT_MAX_FILES)
114   {
115     WARN(":files exhausted!\n");
116     return -1;
117   }
118   MSVCRT_handles[fd] = hand;
119   MSVCRT_flags[fd] = flag;
120
121   /* locate next free slot */
122   if (fd == MSVCRT_fdend)
123     MSVCRT_fdstart = ++MSVCRT_fdend;
124   else
125     while(MSVCRT_fdstart < MSVCRT_fdend &&
126           MSVCRT_handles[MSVCRT_fdstart] != INVALID_HANDLE_VALUE)
127       MSVCRT_fdstart++;
128
129   return fd;
130 }
131
132 /* INTERNAL: Allocate a FILE* for an fd slot
133  * This is done lazily to avoid memory wastage for low level open/write
134  * usage when a FILE* is not requested (but may be later).
135  */
136 static MSVCRT_FILE* msvcrt_alloc_fp(int fd)
137 {
138   TRACE(":fd (%d) allocating FILE*\n",fd);
139   if (fd < 0 || fd >= MSVCRT_fdend ||
140       MSVCRT_handles[fd] == INVALID_HANDLE_VALUE)
141   {
142     WARN(":invalid fd %d\n",fd);
143     SET_THREAD_VAR(doserrno,0);
144     SET_THREAD_VAR(errno,MSVCRT_EBADF);
145     return NULL;
146   }
147   if (!MSVCRT_files[fd])
148   {
149     if ((MSVCRT_files[fd] = MSVCRT_calloc(sizeof(MSVCRT_FILE),1)))
150     {
151       MSVCRT_files[fd]->_file = fd;
152       MSVCRT_files[fd]->_flag = MSVCRT_flags[fd];
153       MSVCRT_files[fd]->_flag &= ~MSVCRT__IOAPPEND; /* mask out, see above */
154     }
155   }
156   TRACE(":got FILE* (%p)\n",MSVCRT_files[fd]);
157   return MSVCRT_files[fd];
158 }
159
160
161 /* INTERNAL: Set up stdin, stderr and stdout */
162 void msvcrt_init_io(void)
163 {
164   int i;
165   memset(MSVCRT__iob,0,3*sizeof(MSVCRT_FILE));
166   MSVCRT_handles[0] = GetStdHandle(STD_INPUT_HANDLE);
167   MSVCRT_flags[0] = MSVCRT__iob[0]._flag = MSVCRT__IOREAD;
168   MSVCRT_handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
169   MSVCRT_flags[1] = MSVCRT__iob[1]._flag = MSVCRT__IOWRT;
170   MSVCRT_handles[2] = GetStdHandle(STD_ERROR_HANDLE);
171   MSVCRT_flags[2] = MSVCRT__iob[2]._flag = MSVCRT__IOWRT;
172
173   TRACE(":handles (%d)(%d)(%d)\n",MSVCRT_handles[0],
174         MSVCRT_handles[1],MSVCRT_handles[2]);
175
176   for (i = 0; i < 3; i++)
177   {
178     /* FILE structs for stdin/out/err are static and never deleted */
179     MSVCRT_files[i] = &MSVCRT__iob[i];
180     MSVCRT__iob[i]._file = i;
181     MSVCRT_tempfiles[i] = NULL;
182   }
183 }
184
185 /*********************************************************************
186  *              __p__iob(MSVCRT.@)
187  */
188 MSVCRT_FILE *__p__iob(void)
189 {
190  return &MSVCRT__iob[0];
191 }
192
193 /*********************************************************************
194  *              _access (MSVCRT.@)
195  */
196 int _access(const char *filename, int mode)
197 {
198   DWORD attr = GetFileAttributesA(filename);
199
200   TRACE("(%s,%d) %ld\n",filename,mode,attr);
201
202   if (!filename || attr == 0xffffffff)
203   {
204     MSVCRT__set_errno(GetLastError());
205     return -1;
206   }
207   if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
208   {
209     MSVCRT__set_errno(ERROR_ACCESS_DENIED);
210     return -1;
211   }
212   return 0;
213 }
214
215 /*********************************************************************
216  *              _waccess (MSVCRT.@)
217  */
218 int _waccess(const WCHAR *filename, int mode)
219 {
220   DWORD attr = GetFileAttributesW(filename);
221
222   TRACE("(%s,%d) %ld\n",debugstr_w(filename),mode,attr);
223
224   if (!filename || attr == 0xffffffff)
225   {
226     MSVCRT__set_errno(GetLastError());
227     return -1;
228   }
229   if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
230   {
231     MSVCRT__set_errno(ERROR_ACCESS_DENIED);
232     return -1;
233   }
234   return 0;
235 }
236
237 /*********************************************************************
238  *              _chmod (MSVCRT.@)
239  */
240 int _chmod(const char *path, int flags)
241 {
242   DWORD oldFlags = GetFileAttributesA(path);
243
244   if (oldFlags != 0x0FFFFFFFF)
245   {
246     DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
247       oldFlags | FILE_ATTRIBUTE_READONLY;
248
249     if (newFlags == oldFlags || SetFileAttributesA(path, newFlags))
250       return 0;
251   }
252   MSVCRT__set_errno(GetLastError());
253   return -1;
254 }
255
256 /*********************************************************************
257  *              _wchmod (MSVCRT.@)
258  */
259 int _wchmod(const WCHAR *path, int flags)
260 {
261   DWORD oldFlags = GetFileAttributesW(path);
262
263   if (oldFlags != 0x0FFFFFFFF)
264   {
265     DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
266       oldFlags | FILE_ATTRIBUTE_READONLY;
267
268     if (newFlags == oldFlags || SetFileAttributesW(path, newFlags))
269       return 0;
270   }
271   MSVCRT__set_errno(GetLastError());
272   return -1;
273 }
274
275 /*********************************************************************
276  *              _unlink (MSVCRT.@)
277  */
278 int _unlink(const char *path)
279 {
280   TRACE("(%s)\n",path);
281   if(DeleteFileA(path))
282     return 0;
283   TRACE("failed (%ld)\n",GetLastError());
284   MSVCRT__set_errno(GetLastError());
285   return -1;
286 }
287
288 /*********************************************************************
289  *              _wunlink (MSVCRT.@)
290  */
291 int _wunlink(const WCHAR *path)
292 {
293   TRACE("(%s)\n",debugstr_w(path));
294   if(DeleteFileW(path))
295     return 0;
296   TRACE("failed (%ld)\n",GetLastError());
297   MSVCRT__set_errno(GetLastError());
298   return -1;
299 }
300
301 /*********************************************************************
302  *              _close (MSVCRT.@)
303  */
304 int _close(int fd)
305 {
306   HANDLE hand = msvcrt_fdtoh(fd);
307
308   TRACE(":fd (%d) handle (%d)\n",fd,hand);
309   if (hand == INVALID_HANDLE_VALUE)
310     return -1;
311
312   /* Dont free std FILE*'s, they are not dynamic */
313   if (fd > 2 && MSVCRT_files[fd])
314     MSVCRT_free(MSVCRT_files[fd]);
315
316   msvcrt_free_fd(fd);
317
318   if (!CloseHandle(hand))
319   {
320     WARN(":failed-last error (%ld)\n",GetLastError());
321     MSVCRT__set_errno(GetLastError());
322     return -1;
323   }
324   if (MSVCRT_tempfiles[fd])
325   {
326     TRACE("deleting temporary file '%s'\n",MSVCRT_tempfiles[fd]);
327     _unlink(MSVCRT_tempfiles[fd]);
328     MSVCRT_free(MSVCRT_tempfiles[fd]);
329     MSVCRT_tempfiles[fd] = NULL;
330   }
331
332   TRACE(":ok\n");
333   return 0;
334 }
335
336 /*********************************************************************
337  *              _commit (MSVCRT.@)
338  */
339 int _commit(int fd)
340 {
341   HANDLE hand = msvcrt_fdtoh(fd);
342
343   TRACE(":fd (%d) handle (%d)\n",fd,hand);
344   if (hand == INVALID_HANDLE_VALUE)
345     return -1;
346
347   if (!FlushFileBuffers(hand))
348   {
349     if (GetLastError() == ERROR_INVALID_HANDLE)
350     {
351       /* FlushFileBuffers fails for console handles
352        * so we ignore this error.
353        */
354       return 0;
355     }
356     TRACE(":failed-last error (%ld)\n",GetLastError());
357     MSVCRT__set_errno(GetLastError());
358     return -1;
359   }
360   TRACE(":ok\n");
361   return 0;
362 }
363
364 /*********************************************************************
365  *              _eof (MSVCRT.@)
366  */
367 int _eof(int fd)
368 {
369   DWORD curpos,endpos;
370   HANDLE hand = msvcrt_fdtoh(fd);
371
372   TRACE(":fd (%d) handle (%d)\n",fd,hand);
373
374   if (hand == INVALID_HANDLE_VALUE)
375     return -1;
376
377   /* If we have a FILE* for this file, the EOF flag
378    * will be set by the read()/write() functions.
379    */
380   if (MSVCRT_files[fd])
381     return MSVCRT_files[fd]->_flag & MSVCRT__IOEOF;
382
383   /* Otherwise we do it the hard way */
384   curpos = SetFilePointer(hand, 0, NULL, SEEK_CUR);
385   endpos = SetFilePointer(hand, 0, NULL, FILE_END);
386
387   if (curpos == endpos)
388     return TRUE;
389
390   SetFilePointer(hand, curpos, 0, FILE_BEGIN);
391   return FALSE;
392 }
393
394 /*********************************************************************
395  *              _fcloseall (MSVCRT.@)
396  */
397 int _fcloseall(void)
398 {
399   int num_closed = 0, i;
400
401   for (i = 3; i < MSVCRT_fdend; i++)
402     if (MSVCRT_handles[i] != INVALID_HANDLE_VALUE)
403     {
404       _close(i);
405       num_closed++;
406     }
407
408   TRACE(":closed (%d) handles\n",num_closed);
409   return num_closed;
410 }
411
412 /*********************************************************************
413  *              _lseek (MSVCRT.@)
414  */
415 LONG _lseek(int fd, LONG offset, int whence)
416 {
417   DWORD ret;
418   HANDLE hand = msvcrt_fdtoh(fd);
419
420   TRACE(":fd (%d) handle (%d)\n",fd,hand);
421   if (hand == INVALID_HANDLE_VALUE)
422     return -1;
423
424   if (whence < 0 || whence > 2)
425   {
426     SET_THREAD_VAR(errno,MSVCRT_EINVAL);
427     return -1;
428   }
429
430   TRACE(":fd (%d) to 0x%08lx pos %s\n",
431         fd,offset,(whence==SEEK_SET)?"SEEK_SET":
432         (whence==SEEK_CUR)?"SEEK_CUR":
433         (whence==SEEK_END)?"SEEK_END":"UNKNOWN");
434
435   if ((ret = SetFilePointer(hand, offset, NULL, whence)) != 0xffffffff)
436   {
437     if (MSVCRT_files[fd])
438       MSVCRT_files[fd]->_flag &= ~MSVCRT__IOEOF;
439     /* FIXME: What if we seek _to_ EOF - is EOF set? */
440     return ret;
441   }
442   TRACE(":error-last error (%ld)\n",GetLastError());
443   if (MSVCRT_files[fd])
444     switch(GetLastError())
445     {
446     case ERROR_NEGATIVE_SEEK:
447     case ERROR_SEEK_ON_DEVICE:
448       MSVCRT__set_errno(GetLastError());
449       MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
450       break;
451     default:
452       break;
453     }
454   return -1;
455 }
456
457 /*********************************************************************
458  *              rewind (MSVCRT.@)
459  */
460 void MSVCRT_rewind(MSVCRT_FILE* file)
461 {
462   TRACE(":file (%p) fd (%d)\n",file,file->_file);
463   _lseek(file->_file,0,SEEK_SET);
464   file->_flag &= ~(MSVCRT__IOEOF | MSVCRT__IOERR);
465 }
466
467 /*********************************************************************
468  *              _fdopen (MSVCRT.@)
469  */
470 MSVCRT_FILE* _fdopen(int fd, const char *mode)
471 {
472   MSVCRT_FILE* file = msvcrt_alloc_fp(fd);
473
474   TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,mode,file);
475   if (file)
476     MSVCRT_rewind(file);
477
478   return file;
479 }
480
481 /*********************************************************************
482  *              _wfdopen (MSVCRT.@)
483  */
484 MSVCRT_FILE* _wfdopen(int fd, const WCHAR *mode)
485 {
486   MSVCRT_FILE* file = msvcrt_alloc_fp(fd);
487
488   TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,debugstr_w(mode),file);
489   if (file)
490     MSVCRT_rewind(file);
491
492   return file;
493 }
494
495 /*********************************************************************
496  *              _filelength (MSVCRT.@)
497  */
498 LONG _filelength(int fd)
499 {
500   LONG curPos = _lseek(fd, 0, SEEK_CUR);
501   if (curPos != -1)
502   {
503     LONG endPos = _lseek(fd, 0, SEEK_END);
504     if (endPos != -1)
505     {
506       if (endPos != curPos)
507         _lseek(fd, curPos, SEEK_SET);
508       return endPos;
509     }
510   }
511   return -1;
512 }
513
514 /*********************************************************************
515  *              _fileno (MSVCRT.@)
516  */
517 int _fileno(MSVCRT_FILE* file)
518 {
519   TRACE(":FILE* (%p) fd (%d)\n",file,file->_file);
520   return file->_file;
521 }
522
523 /*********************************************************************
524  *              _flushall (MSVCRT.@)
525  */
526 int _flushall(void)
527 {
528   int num_flushed = 0, i = 3;
529
530   while(i < MSVCRT_fdend)
531     if (MSVCRT_handles[i] != INVALID_HANDLE_VALUE)
532     {
533       if (_commit(i) == -1)
534         if (MSVCRT_files[i])
535           MSVCRT_files[i]->_flag |= MSVCRT__IOERR;
536       num_flushed++;
537     }
538
539   TRACE(":flushed (%d) handles\n",num_flushed);
540   return num_flushed;
541 }
542
543 /*********************************************************************
544  *              _fstat (MSVCRT.@)
545  */
546 int _fstat(int fd, struct _stat* buf)
547 {
548   DWORD dw;
549   BY_HANDLE_FILE_INFORMATION hfi;
550   HANDLE hand = msvcrt_fdtoh(fd);
551
552   TRACE(":fd (%d) stat (%p)\n",fd,buf);
553   if (hand == INVALID_HANDLE_VALUE)
554     return -1;
555
556   if (!buf)
557   {
558     WARN(":failed-NULL buf\n");
559     MSVCRT__set_errno(ERROR_INVALID_PARAMETER);
560     return -1;
561   }
562
563   memset(&hfi, 0, sizeof(hfi));
564   memset(buf, 0, sizeof(struct _stat));
565   if (!GetFileInformationByHandle(hand, &hfi))
566   {
567     WARN(":failed-last error (%ld)\n",GetLastError());
568     MSVCRT__set_errno(ERROR_INVALID_PARAMETER);
569     return -1;
570   }
571   FIXME(":dwFileAttributes = %ld, mode set to 0\n",hfi.dwFileAttributes);
572   buf->st_nlink = hfi.nNumberOfLinks;
573   buf->st_size  = hfi.nFileSizeLow;
574   RtlTimeToSecondsSince1970(&hfi.ftLastAccessTime, &dw);
575   buf->st_atime = dw;
576   RtlTimeToSecondsSince1970(&hfi.ftLastWriteTime, &dw);
577   buf->st_mtime = buf->st_ctime = dw;
578   return 0;
579 }
580
581 /*********************************************************************
582  *              _futime (MSVCRT.@)
583  */
584 int _futime(int fd, struct _utimbuf *t)
585 {
586   HANDLE hand = msvcrt_fdtoh(fd);
587   FILETIME at, wt;
588
589   if (!t)
590   {
591     MSVCRT_time_t currTime;
592     MSVCRT_time(&currTime);
593     RtlSecondsSince1970ToTime(currTime, &at);
594     memcpy(&wt, &at, sizeof(wt));
595   }
596   else
597   {
598     RtlSecondsSince1970ToTime(t->actime, &at);
599     if (t->actime == t->modtime)
600       memcpy(&wt, &at, sizeof(wt));
601     else
602       RtlSecondsSince1970ToTime(t->modtime, &wt);
603   }
604
605   if (!SetFileTime(hand, NULL, &at, &wt))
606   {
607     MSVCRT__set_errno(GetLastError());
608     return -1 ;
609   }
610   return 0;
611 }
612
613 /*********************************************************************
614  *              _get_osfhandle (MSVCRT.@)
615  */
616 long _get_osfhandle(int fd)
617 {
618   HANDLE hand = msvcrt_fdtoh(fd);
619   HANDLE newhand = hand;
620   TRACE(":fd (%d) handle (%d)\n",fd,hand);
621
622   if (hand != INVALID_HANDLE_VALUE)
623   {
624     /* FIXME: I'm not convinced that I should be copying the
625      * handle here - it may be leaked if the app doesn't
626      * close it (and the API docs dont say that it should)
627      * Not duplicating it means that it can't be inherited
628      * and so lcc's wedit doesn't cope when it passes it to
629      * child processes. I've an idea that it should either
630      * be copied by CreateProcess, or marked as inheritable
631      * when initialised, or maybe both? JG 21-9-00.
632      */
633     DuplicateHandle(GetCurrentProcess(),hand,GetCurrentProcess(),
634                     &newhand,0,TRUE,DUPLICATE_SAME_ACCESS);
635   }
636   return newhand;
637 }
638
639 /*********************************************************************
640  *              _isatty (MSVCRT.@)
641  */
642 int _isatty(int fd)
643 {
644   HANDLE hand = msvcrt_fdtoh(fd);
645
646   TRACE(":fd (%d) handle (%d)\n",fd,hand);
647   if (hand == INVALID_HANDLE_VALUE)
648     return 0;
649
650   return GetFileType(hand) == FILE_TYPE_CHAR? 1 : 0;
651 }
652
653 /*********************************************************************
654  *              _mktemp (MSVCRT.@)
655  */
656 char *_mktemp(char *pattern)
657 {
658   int numX = 0;
659   char *retVal = pattern;
660   int id;
661   char letter = 'a';
662
663   while(*pattern)
664     numX = (*pattern++ == 'X')? numX + 1 : 0;
665   if (numX < 5)
666     return NULL;
667   pattern--;
668   id = GetCurrentProcessId();
669   numX = 6;
670   while(numX--)
671   {
672     int tempNum = id / 10;
673     *pattern-- = id - (tempNum * 10) + '0';
674     id = tempNum;
675   }
676   pattern++;
677   do
678   {
679     if (GetFileAttributesA(retVal) == 0xFFFFFFFF &&
680         GetLastError() == ERROR_FILE_NOT_FOUND)
681       return retVal;
682     *pattern = letter++;
683   } while(letter != '|');
684   return NULL;
685 }
686
687 /*********************************************************************
688  *              _wmktemp (MSVCRT.@)
689  */
690 WCHAR *_wmktemp(WCHAR *pattern)
691 {
692   int numX = 0;
693   WCHAR *retVal = pattern;
694   int id;
695   WCHAR letter = (WCHAR)L'a';
696
697   while(*pattern)
698     numX = (*pattern++ == (WCHAR)L'X')? numX + 1 : 0;
699   if (numX < 5)
700     return NULL;
701   pattern--;
702   id = GetCurrentProcessId();
703   numX = 6;
704   while(numX--)
705   {
706     int tempNum = id / 10;
707     *pattern-- = id - (tempNum * 10) + (WCHAR)L'0';
708     id = tempNum;
709   }
710   pattern++;
711   do
712   {
713     if (GetFileAttributesW(retVal) == 0xFFFFFFFF &&
714         GetLastError() == ERROR_FILE_NOT_FOUND)
715       return retVal;
716     *pattern = letter++;
717   } while(letter != (WCHAR)L'|');
718   return NULL;
719 }
720
721 /*********************************************************************
722  *              _open (MSVCRT.@)
723  */
724 int _open(const char *path,int flags,...)
725 {
726   DWORD access = 0, creation = 0;
727   int ioflag = 0, fd;
728   HANDLE hand;
729   SECURITY_ATTRIBUTES sa;
730   
731   TRACE(":file (%s) mode 0x%04x\n",path,flags);
732
733   switch(flags & (_O_RDONLY | _O_WRONLY | _O_RDWR))
734   {
735   case _O_RDONLY:
736     access |= GENERIC_READ;
737     ioflag |= MSVCRT__IOREAD;
738     break;
739   case _O_WRONLY:
740     access |= GENERIC_WRITE;
741     ioflag |= MSVCRT__IOWRT;
742     break;
743   case _O_RDWR:
744     access |= GENERIC_WRITE | GENERIC_READ;
745     ioflag |= MSVCRT__IORW;
746     break;
747   }
748
749   if (flags & _O_CREAT)
750   {
751     if (flags & _O_EXCL)
752       creation = CREATE_NEW;
753     else if (flags & _O_TRUNC)
754       creation = CREATE_ALWAYS;
755     else
756       creation = OPEN_ALWAYS;
757   }
758   else  /* no _O_CREAT */
759   {
760     if (flags & _O_TRUNC)
761       creation = TRUNCATE_EXISTING;
762     else
763       creation = OPEN_EXISTING;
764   }
765   if (flags & _O_APPEND)
766     ioflag |= MSVCRT__IOAPPEND;
767
768
769   flags |= _O_BINARY; /* FIXME: Default to text */
770
771   if (flags & _O_TEXT)
772   {
773     /* Dont warn when writing */
774     if (ioflag & GENERIC_READ)
775       FIXME(":TEXT node not implemented\n");
776     flags &= ~_O_TEXT;
777   }
778
779   if (flags & ~(_O_BINARY|_O_TEXT|_O_APPEND|_O_TRUNC|_O_EXCL
780                 |_O_CREAT|_O_RDWR|_O_TEMPORARY))
781     TRACE(":unsupported flags 0x%04x\n",flags);
782       
783   sa.nLength              = sizeof( SECURITY_ATTRIBUTES );
784   sa.lpSecurityDescriptor = NULL;
785   sa.bInheritHandle       = TRUE;
786
787   hand = CreateFileA(path, access, FILE_SHARE_READ | FILE_SHARE_WRITE,
788                       &sa, creation, FILE_ATTRIBUTE_NORMAL, 0);
789
790   if (hand == INVALID_HANDLE_VALUE)
791   {
792     WARN(":failed-last error (%ld)\n",GetLastError());
793     MSVCRT__set_errno(GetLastError());
794     return -1;
795   }
796
797   fd = msvcrt_alloc_fd(hand, ioflag);
798
799   TRACE(":fd (%d) handle (%d)\n",fd, hand);
800
801   if (fd > 0)
802   {
803     if (flags & _O_TEMPORARY)
804       MSVCRT_tempfiles[fd] = _strdup(path);
805     if (ioflag & MSVCRT__IOAPPEND)
806       _lseek(fd, 0, FILE_END);
807   }
808
809   return fd;
810 }
811
812 /*********************************************************************
813  *              _wopen (MSVCRT.@)
814  */
815 int _wopen(const WCHAR *path,int flags,...)
816 {
817   const unsigned int len = strlenW(path);
818   char *patha = MSVCRT_calloc(len + 1,1);
819   if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
820   {
821     int retval = _open(patha,flags);
822     MSVCRT_free(patha);
823     return retval;
824   }
825
826   MSVCRT__set_errno(GetLastError());
827   return -1;
828 }
829
830 /*********************************************************************
831  *              _sopen (MSVCRT.@)
832  */
833 int MSVCRT__sopen(const char *path,int oflags,int shflags)
834 {
835   return _open(path, oflags | shflags);
836 }
837
838 /*********************************************************************
839  *              _creat (MSVCRT.@)
840  */
841 int _creat(const char *path, int flags)
842 {
843   int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
844   return _open(path, usedFlags);
845 }
846
847 /*********************************************************************
848  *              _wcreat (MSVCRT.@)
849  */
850 int _wcreat(const WCHAR *path, int flags)
851 {
852   int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
853   return _wopen(path, usedFlags);
854 }
855
856 /*********************************************************************
857  *              _open_osfhandle (MSVCRT.@)
858  */
859 int _open_osfhandle(long hand, int flags)
860 {
861   int fd = msvcrt_alloc_fd(hand,flags);
862   TRACE(":handle (%ld) fd (%d)\n",hand,fd);
863   return fd;
864 }
865
866 /*********************************************************************
867  *              _rmtmp (MSVCRT.@)
868  */
869 int _rmtmp(void)
870 {
871   int num_removed = 0, i;
872
873   for (i = 3; i < MSVCRT_fdend; i++)
874     if (MSVCRT_tempfiles[i])
875     {
876       _close(i);
877       num_removed++;
878     }
879
880   if (num_removed)
881     TRACE(":removed (%d) temp files\n",num_removed);
882   return num_removed;
883 }
884
885 /*********************************************************************
886  *              _read (MSVCRT.@)
887  */
888 int _read(int fd, void *buf, unsigned int count)
889 {
890   DWORD num_read;
891   HANDLE hand = msvcrt_fdtoh(fd);
892
893   /* Dont trace small reads, it gets *very* annoying */
894   if (count > 4)
895     TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
896   if (hand == INVALID_HANDLE_VALUE)
897     return -1;
898
899   /* Set _cnt to 0 so optimised binaries will call our implementation
900    * of putc/getc. See _filbuf/_flsbuf comments.
901    */
902   if (MSVCRT_files[fd])
903     MSVCRT_files[fd]->_cnt = 0;
904
905   if (ReadFile(hand, buf, count, &num_read, NULL))
906   {
907     if (num_read != count && MSVCRT_files[fd])
908     {
909       TRACE(":EOF\n");
910       MSVCRT_files[fd]->_flag |= MSVCRT__IOEOF;
911     }
912     return num_read;
913   }
914   TRACE(":failed-last error (%ld)\n",GetLastError());
915   if (MSVCRT_files[fd])
916      MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
917   return -1;
918 }
919
920 /*********************************************************************
921  *              _getw (MSVCRT.@)
922  */
923 int _getw(MSVCRT_FILE* file)
924 {
925   int i;
926   if (_read(file->_file, &i, sizeof(int)) != 1)
927     return MSVCRT_EOF;
928   return i;
929 }
930
931 /*********************************************************************
932  *              _setmode (MSVCRT.@)
933  */
934 int _setmode(int fd,int mode)
935 {
936   if (mode & _O_TEXT)
937     FIXME("fd (%d) mode (%d) TEXT not implemented\n",fd,mode);
938   return 0;
939 }
940
941 /*********************************************************************
942  *              _stat (MSVCRT.@)
943  */
944 int _stat(const char* path, struct _stat * buf)
945 {
946   DWORD dw;
947   WIN32_FILE_ATTRIBUTE_DATA hfi;
948   unsigned short mode = MSVCRT_S_IREAD;
949   int plen;
950
951   TRACE(":file (%s) buf(%p)\n",path,buf);
952
953   if (!GetFileAttributesExA(path, GetFileExInfoStandard, &hfi))
954   {
955       TRACE("failed (%ld)\n",GetLastError());
956       MSVCRT__set_errno(ERROR_FILE_NOT_FOUND);
957       return -1;
958   }
959
960   memset(buf,0,sizeof(struct _stat));
961
962   /* FIXME: rdev isnt drive num,despite what the docs say-what is it? 
963      Bon 011120: This FIXME seems incorrect 
964                  Also a letter as first char isn't enough to be classify 
965                  as drive letter
966   */
967   if (isalpha(*path)&& (*(path+1)==':'))
968     buf->st_dev = buf->st_rdev = toupper(*path) - 'A'; /* drive num */
969   else
970     buf->st_dev = buf->st_rdev = _getdrive() - 1;
971
972   plen = strlen(path);
973
974   /* Dir, or regular file? */
975   if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
976       (path[plen-1] == '\\'))
977     mode |= (_S_IFDIR | MSVCRT_S_IEXEC);
978   else
979   {
980     mode |= _S_IFREG;
981     /* executable? */
982     if (plen > 6 && path[plen-4] == '.')  /* shortest exe: "\x.exe" */
983     {
984       unsigned int ext = tolower(path[plen-1]) | (tolower(path[plen-2]) << 8) |
985                                  (tolower(path[plen-3]) << 16);
986       if (ext == EXE || ext == BAT || ext == CMD || ext == COM)
987           mode |= MSVCRT_S_IEXEC;
988     }
989   }
990
991   if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
992     mode |= MSVCRT_S_IWRITE;
993
994   buf->st_mode  = mode;
995   buf->st_nlink = 1;
996   buf->st_size  = hfi.nFileSizeLow;
997   RtlTimeToSecondsSince1970(&hfi.ftLastAccessTime, &dw);
998   buf->st_atime = dw;
999   RtlTimeToSecondsSince1970(&hfi.ftLastWriteTime, &dw);
1000   buf->st_mtime = buf->st_ctime = dw;
1001   TRACE("\n%d %d %d %ld %ld %ld\n", buf->st_mode,buf->st_nlink,buf->st_size,
1002     buf->st_atime,buf->st_mtime, buf->st_ctime);
1003   return 0;
1004 }
1005
1006 /*********************************************************************
1007  *              _wstat (MSVCRT.@)
1008  */
1009 int _wstat(const WCHAR* path, struct _stat * buf)
1010 {
1011   DWORD dw;
1012   WIN32_FILE_ATTRIBUTE_DATA hfi;
1013   unsigned short mode = MSVCRT_S_IREAD;
1014   int plen;
1015
1016   TRACE(":file (%s) buf(%p)\n",debugstr_w(path),buf);
1017
1018   if (!GetFileAttributesExW(path, GetFileExInfoStandard, &hfi))
1019   {
1020       TRACE("failed (%ld)\n",GetLastError());
1021       MSVCRT__set_errno(ERROR_FILE_NOT_FOUND);
1022       return -1;
1023   }
1024
1025   memset(buf,0,sizeof(struct _stat));
1026
1027   /* FIXME: rdev isn't drive num, despite what the docs says-what is it? */
1028   if (MSVCRT_iswalpha(*path))
1029     buf->st_dev = buf->st_rdev = toupperW(*path - (WCHAR)L'A'); /* drive num */
1030   else
1031     buf->st_dev = buf->st_rdev = _getdrive() - 1;
1032
1033   plen = strlenW(path);
1034
1035   /* Dir, or regular file? */
1036   if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1037       (path[plen-1] == (WCHAR)L'\\'))
1038     mode |= (_S_IFDIR | MSVCRT_S_IEXEC);
1039   else
1040   {
1041     mode |= _S_IFREG;
1042     /* executable? */
1043     if (plen > 6 && path[plen-4] == (WCHAR)L'.')  /* shortest exe: "\x.exe" */
1044     {
1045       ULONGLONG ext = tolowerW(path[plen-1]) | (tolowerW(path[plen-2]) << 16) |
1046                                ((ULONGLONG)tolowerW(path[plen-3]) << 32);
1047       if (ext == WCEXE || ext == WCBAT || ext == WCCMD || ext == WCCOM)
1048         mode |= MSVCRT_S_IEXEC;
1049     }
1050   }
1051
1052   if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1053     mode |= MSVCRT_S_IWRITE;
1054
1055   buf->st_mode  = mode;
1056   buf->st_nlink = 1;
1057   buf->st_size  = hfi.nFileSizeLow;
1058   RtlTimeToSecondsSince1970(&hfi.ftLastAccessTime, &dw);
1059   buf->st_atime = dw;
1060   RtlTimeToSecondsSince1970(&hfi.ftLastWriteTime, &dw);
1061   buf->st_mtime = buf->st_ctime = dw;
1062   TRACE("\n%d %d %d %ld %ld %ld\n", buf->st_mode,buf->st_nlink,buf->st_size,
1063         buf->st_atime,buf->st_mtime, buf->st_ctime);
1064   return 0;
1065 }
1066
1067 /*********************************************************************
1068  *              _tell (MSVCRT.@)
1069  */
1070 LONG _tell(int fd)
1071 {
1072   return _lseek(fd, 0, SEEK_CUR);
1073 }
1074
1075 /*********************************************************************
1076  *              _tempnam (MSVCRT.@)
1077  */
1078 char *_tempnam(const char *dir, const char *prefix)
1079 {
1080   char tmpbuf[MAX_PATH];
1081
1082   TRACE("dir (%s) prefix (%s)\n",dir,prefix);
1083   if (GetTempFileNameA(dir,prefix,0,tmpbuf))
1084   {
1085     TRACE("got name (%s)\n",tmpbuf);
1086     return _strdup(tmpbuf);
1087   }
1088   TRACE("failed (%ld)\n",GetLastError());
1089   return NULL;
1090 }
1091
1092 /*********************************************************************
1093  *              _wtempnam (MSVCRT.@)
1094  */
1095 WCHAR *_wtempnam(const WCHAR *dir, const WCHAR *prefix)
1096 {
1097   WCHAR tmpbuf[MAX_PATH];
1098
1099   TRACE("dir (%s) prefix (%s)\n",debugstr_w(dir),debugstr_w(prefix));
1100   if (GetTempFileNameW(dir,prefix,0,tmpbuf))
1101   {
1102     TRACE("got name (%s)\n",debugstr_w(tmpbuf));
1103     return _wcsdup(tmpbuf);
1104   }
1105   TRACE("failed (%ld)\n",GetLastError());
1106   return NULL;
1107 }
1108
1109 /*********************************************************************
1110  *              _umask (MSVCRT.@)
1111  */
1112 int _umask(int umask)
1113 {
1114   int old_umask = MSVCRT_umask;
1115   TRACE("(%d)\n",umask);
1116   MSVCRT_umask = umask;
1117   return old_umask;
1118 }
1119
1120 /*********************************************************************
1121  *              _utime (MSVCRT.@)
1122  */
1123 int _utime(const char* path, struct _utimbuf *t)
1124 {
1125   int fd = _open(path, _O_WRONLY | _O_BINARY);
1126
1127   if (fd > 0)
1128   {
1129     int retVal = _futime(fd, t);
1130     _close(fd);
1131     return retVal;
1132   }
1133   return -1;
1134 }
1135
1136 /*********************************************************************
1137  *              _wutime (MSVCRT.@)
1138  */
1139 int _wutime(const WCHAR* path, struct _utimbuf *t)
1140 {
1141   int fd = _wopen(path, _O_WRONLY | _O_BINARY);
1142
1143   if (fd > 0)
1144   {
1145     int retVal = _futime(fd, t);
1146     _close(fd);
1147     return retVal;
1148   }
1149   return -1;
1150 }
1151
1152 /*********************************************************************
1153  *              _write (MSVCRT.@)
1154  */
1155 int _write(int fd, const void* buf, unsigned int count)
1156 {
1157   DWORD num_written;
1158   HANDLE hand = msvcrt_fdtoh(fd);
1159
1160   /* Dont trace small writes, it gets *very* annoying */
1161 //  if (count > 32)
1162 //    TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
1163   if (hand == INVALID_HANDLE_VALUE)
1164     return -1;
1165
1166   /* If appending, go to EOF */
1167   if (MSVCRT_flags[fd] & MSVCRT__IOAPPEND)
1168     _lseek(fd, 0, FILE_END);
1169
1170   /* Set _cnt to 0 so optimised binaries will call our implementation
1171    * of putc/getc.
1172    */
1173   if (MSVCRT_files[fd])
1174     MSVCRT_files[fd]->_cnt = 0;
1175
1176   if (WriteFile(hand, buf, count, &num_written, NULL)
1177       &&  (num_written == count))
1178     return num_written;
1179
1180   TRACE(":failed-last error (%ld)\n",GetLastError());
1181   if (MSVCRT_files[fd])
1182      MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
1183
1184   return -1;
1185 }
1186
1187 /*********************************************************************
1188  *              _putw (MSVCRT.@)
1189  */
1190 int _putw(int val, MSVCRT_FILE* file)
1191 {
1192   return _write(file->_file, &val, sizeof(val)) == 1? val : MSVCRT_EOF;
1193 }
1194
1195 /*********************************************************************
1196  *              clearerr (MSVCRT.@)
1197  */
1198 void MSVCRT_clearerr(MSVCRT_FILE* file)
1199 {
1200   TRACE(":file (%p) fd (%d)\n",file,file->_file);
1201   file->_flag &= ~(MSVCRT__IOERR | MSVCRT__IOEOF);
1202 }
1203
1204 /*********************************************************************
1205  *              fclose (MSVCRT.@)
1206  */
1207 int MSVCRT_fclose(MSVCRT_FILE* file)
1208 {
1209   int r;
1210   r=_close(file->_file);
1211   return ((r==MSVCRT_EOF) || (file->_flag & MSVCRT__IOERR) ? MSVCRT_EOF : 0);
1212 }
1213
1214 /*********************************************************************
1215  *              feof (MSVCRT.@)
1216  */
1217 int MSVCRT_feof(MSVCRT_FILE* file)
1218 {
1219   return file->_flag & MSVCRT__IOEOF;
1220 }
1221
1222 /*********************************************************************
1223  *              ferror (MSVCRT.@)
1224  */
1225 int MSVCRT_ferror(MSVCRT_FILE* file)
1226 {
1227   return file->_flag & MSVCRT__IOERR;
1228 }
1229
1230 /*********************************************************************
1231  *              fflush (MSVCRT.@)
1232  */
1233 int MSVCRT_fflush(MSVCRT_FILE* file)
1234 {
1235   return _commit(file->_file);
1236 }
1237
1238 /*********************************************************************
1239  *              fgetc (MSVCRT.@)
1240  */
1241 int MSVCRT_fgetc(MSVCRT_FILE* file)
1242 {
1243   char c;
1244   if (_read(file->_file,&c,1) != 1)
1245     return MSVCRT_EOF;
1246   return c;
1247 }
1248
1249 /*********************************************************************
1250  *              _fgetchar (MSVCRT.@)
1251  */
1252 int _fgetchar(void)
1253 {
1254   return MSVCRT_fgetc(MSVCRT_stdin);
1255 }
1256
1257 /*********************************************************************
1258  *              _filbuf (MSVCRT.@)
1259  */
1260 int _filbuf(MSVCRT_FILE* file)
1261 {
1262   return MSVCRT_fgetc(file);
1263 }
1264
1265 /*********************************************************************
1266  *              fgetpos (MSVCRT.@)
1267  */
1268 int MSVCRT_fgetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
1269 {
1270   *pos = _tell(file->_file);
1271   return (*pos == -1? -1 : 0);
1272 }
1273
1274 /*********************************************************************
1275  *              fgets (MSVCRT.@)
1276  */
1277 char *MSVCRT_fgets(char *s, int size, MSVCRT_FILE* file)
1278 {
1279   int    cc;
1280   char * buf_start = s;
1281
1282   TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
1283         file,file->_file,s,size);
1284
1285   /* BAD, for the whole WINE process blocks... just done this way to test
1286    * windows95's ftp.exe.
1287    * JG - Is this true now we use ReadFile() on stdin too?
1288    */
1289   for(cc = MSVCRT_fgetc(file); cc != MSVCRT_EOF && cc != '\n';
1290       cc = MSVCRT_fgetc(file))
1291     if (cc != '\r')
1292     {
1293       if (--size <= 0) break;
1294       *s++ = (char)cc;
1295     }
1296   if ((cc == MSVCRT_EOF) && (s == buf_start)) /* If nothing read, return 0*/
1297   {
1298     TRACE(":nothing read\n");
1299     return 0;
1300   }
1301   if (cc == '\n')
1302     if (--size > 0)
1303       *s++ = '\n';
1304   *s = '\0';
1305   TRACE(":got '%s'\n", buf_start);
1306   return buf_start;
1307 }
1308
1309 /*********************************************************************
1310  *              fgetwc (MSVCRT.@)
1311  */
1312 MSVCRT_wint_t MSVCRT_fgetwc(MSVCRT_FILE* file)
1313 {
1314   MSVCRT_wint_t wc;
1315   if (_read(file->_file, &wc, sizeof(wc)) != sizeof(wc))
1316     return MSVCRT_WEOF;
1317   return wc;
1318 }
1319
1320 /*********************************************************************
1321  *              getwc (MSVCRT.@)
1322  */
1323 MSVCRT_wint_t MSVCRT_getwc(MSVCRT_FILE* file)
1324 {
1325   return MSVCRT_fgetwc(file);
1326 }
1327
1328 /*********************************************************************
1329  *              _fgetwchar (MSVCRT.@)
1330  */
1331 MSVCRT_wint_t _fgetwchar(void)
1332 {
1333   return MSVCRT_fgetwc(MSVCRT_stdin);
1334 }
1335
1336 /*********************************************************************
1337  *              getwchar (MSVCRT.@)
1338  */
1339 MSVCRT_wint_t MSVCRT_getwchar(void)
1340 {
1341   return _fgetwchar();
1342 }
1343
1344 /*********************************************************************
1345  *              fputwc (MSVCRT.@)
1346  */
1347 MSVCRT_wint_t MSVCRT_fputwc(MSVCRT_wint_t wc, MSVCRT_FILE* file)
1348 {
1349   if (_write(file->_file, &wc, sizeof(wc)) != sizeof(wc))
1350     return MSVCRT_WEOF;
1351   return wc;
1352 }
1353
1354 /*********************************************************************
1355  *              _fputwchar (MSVCRT.@)
1356  */
1357 MSVCRT_wint_t _fputwchar(MSVCRT_wint_t wc)
1358 {
1359   return MSVCRT_fputwc(wc, MSVCRT_stdout);
1360 }
1361
1362 /*********************************************************************
1363  *              fopen (MSVCRT.@)
1364  */
1365 MSVCRT_FILE* MSVCRT_fopen(const char *path, const char *mode)
1366 {
1367   MSVCRT_FILE* file;
1368   int flags = 0, plus = 0, fd;
1369   const char* search = mode;
1370
1371   TRACE("(%s,%s)\n",path,mode);
1372
1373   while (*search)
1374     if (*search++ == '+')
1375       plus = 1;
1376
1377   /* map mode string to open() flags. "man fopen" for possibilities. */
1378   switch(*mode++)
1379   {
1380   case 'R': case 'r':
1381     flags = (plus ? _O_RDWR : _O_RDONLY);
1382     break;
1383   case 'W': case 'w':
1384     flags = _O_CREAT | _O_TRUNC | (plus  ? _O_RDWR : _O_WRONLY);
1385     break;
1386   case 'A': case 'a':
1387     flags = _O_CREAT | _O_APPEND | (plus  ? _O_RDWR : _O_WRONLY);
1388     break;
1389   default:
1390     return NULL;
1391   }
1392
1393   while (*mode)
1394     switch (*mode++)
1395     {
1396     case 'B': case 'b':
1397       flags |=  _O_BINARY;
1398       flags &= ~_O_TEXT;
1399       break;
1400     case 'T': case 't':
1401       flags |=  _O_TEXT;
1402       flags &= ~_O_BINARY;
1403       break;
1404     case '+':
1405       break;
1406     default:
1407       FIXME(":unknown flag %c not supported\n",mode[-1]);
1408     }
1409
1410   fd = _open(path, flags);
1411
1412   if (fd < 0)
1413     return NULL;
1414
1415   file = msvcrt_alloc_fp(fd);
1416   TRACE(":got (%p)\n",file);
1417   if (!file)
1418     _close(fd);
1419
1420   return file;
1421 }
1422
1423 /*********************************************************************
1424  *              _wfopen (MSVCRT.@)
1425  */
1426 MSVCRT_FILE *_wfopen(const WCHAR *path, const WCHAR *mode)
1427 {
1428   const unsigned int plen = strlenW(path), mlen = strlenW(mode);
1429   char *patha = MSVCRT_calloc(plen + 1, 1);
1430   char *modea = MSVCRT_calloc(mlen + 1, 1);
1431
1432   TRACE("(%s,%s)\n",debugstr_w(path),debugstr_w(mode));
1433
1434   if (patha && modea &&
1435       WideCharToMultiByte(CP_ACP,0,path,plen,patha,plen,NULL,NULL) &&
1436       WideCharToMultiByte(CP_ACP,0,mode,mlen,modea,mlen,NULL,NULL))
1437   {
1438     MSVCRT_FILE *retval = MSVCRT_fopen(patha,modea);
1439     MSVCRT_free(patha);
1440     MSVCRT_free(modea);
1441     return retval;
1442   }
1443
1444   MSVCRT__set_errno(GetLastError());
1445   return NULL;
1446 }
1447
1448 /*********************************************************************
1449  *              _fsopen (MSVCRT.@)
1450  */
1451 MSVCRT_FILE*  _fsopen(const char *path, const char *mode, int share)
1452 {
1453   FIXME(":(%s,%s,%d),ignoring share mode!\n",path,mode,share);
1454   return MSVCRT_fopen(path,mode);
1455 }
1456
1457 /*********************************************************************
1458  *              _wfsopen (MSVCRT.@)
1459  */
1460 MSVCRT_FILE*  _wfsopen(const WCHAR *path, const WCHAR *mode, int share)
1461 {
1462   FIXME(":(%s,%s,%d),ignoring share mode!\n",
1463         debugstr_w(path),debugstr_w(mode),share);
1464   return _wfopen(path,mode);
1465 }
1466
1467 /*********************************************************************
1468  *              fputc (MSVCRT.@)
1469  */
1470 int MSVCRT_fputc(int c, MSVCRT_FILE* file)
1471 {
1472   return _write(file->_file, &c, 1) == 1? c : MSVCRT_EOF;
1473 }
1474
1475 /*********************************************************************
1476  *              _flsbuf (MSVCRT.@)
1477  */
1478 int _flsbuf(int c, MSVCRT_FILE* file)
1479 {
1480   return MSVCRT_fputc(c,file);
1481 }
1482
1483 /*********************************************************************
1484  *              _fputchar (MSVCRT.@)
1485  */
1486 int _fputchar(int c)
1487 {
1488   return MSVCRT_fputc(c, MSVCRT_stdout);
1489 }
1490
1491 /*********************************************************************
1492  *              fread (MSVCRT.@)
1493  */
1494 MSVCRT_size_t MSVCRT_fread(void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
1495 {
1496   int read = _read(file->_file,ptr, size * nmemb);
1497   if (read <= 0)
1498     return 0;
1499   return read / size;
1500 }
1501
1502 /*********************************************************************
1503  *              freopen (MSVCRT.@)
1504  *
1505  */
1506 MSVCRT_FILE* MSVCRT_freopen(const char *path, const char *mode,MSVCRT_FILE* file)
1507 {
1508   MSVCRT_FILE* newfile;
1509   int fd;
1510
1511   TRACE(":path (%p) mode (%s) file (%p) fd (%d)\n",path,mode,file,file->_file);
1512   if (!file || ((fd = file->_file) < 0) || fd > MSVCRT_fdend)
1513     return NULL;
1514
1515   if (fd > 2)
1516   {
1517     FIXME(":reopen on user file not implemented!\n");
1518     MSVCRT__set_errno(ERROR_CALL_NOT_IMPLEMENTED);
1519     return NULL;
1520   }
1521
1522   /* first, create the new file */
1523   if ((newfile = MSVCRT_fopen(path,mode)) == NULL)
1524     return NULL;
1525
1526   if (fd < 3 && SetStdHandle(fd == 0 ? STD_INPUT_HANDLE :
1527      (fd == 1? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE),
1528       MSVCRT_handles[newfile->_file]))
1529   {
1530     /* Redirecting std handle to file , copy over.. */
1531     MSVCRT_handles[fd] = MSVCRT_handles[newfile->_file];
1532     MSVCRT_flags[fd] = MSVCRT_flags[newfile->_file];
1533     memcpy(&MSVCRT__iob[fd], newfile, sizeof (MSVCRT_FILE));
1534     MSVCRT__iob[fd]._file = fd;
1535     /* And free up the resources allocated by fopen, but
1536      * not the HANDLE we copied. */
1537     MSVCRT_free(MSVCRT_files[fd]);
1538     msvcrt_free_fd(newfile->_file);
1539     return &MSVCRT__iob[fd];
1540   }
1541
1542   WARN(":failed-last error (%ld)\n",GetLastError());
1543   MSVCRT_fclose(newfile);
1544   MSVCRT__set_errno(GetLastError());
1545   return NULL;
1546 }
1547
1548 /*********************************************************************
1549  *              fsetpos (MSVCRT.@)
1550  */
1551 int MSVCRT_fsetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
1552 {
1553   return _lseek(file->_file,*pos,SEEK_SET);
1554 }
1555
1556 /* helper function for fscanf.  Returns the value of character c in the
1557  * given base, or -1 if the given character is not a digit of the base.
1558  */
1559 static int char2digit(char c, int base) {
1560     if ((c>='0') && (c<='9') && (c<='0'+base-1)) return (c-'0');
1561     if (base<=10) return -1;
1562     if ((c>='A') && (c<='Z') && (c<='A'+base-11)) return (c-'A'+10);
1563     if ((c>='a') && (c<='z') && (c<='a'+base-11)) return (c-'a'+10);
1564     return -1;
1565 }
1566
1567 /*********************************************************************
1568  *              fscanf (MSVCRT.@)
1569  * Implemented based on 
1570  * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/html/_crt_format_specification_fields_.2d_.scanf_and_wscanf_functions.asp
1571  * Extended by C. Scott Ananian <cananian@alumni.princeton.edu> to handle
1572  * more types of format spec.
1573  */
1574 int MSVCRT_fscanf(MSVCRT_FILE* file, const char *format, ...)
1575 {
1576     /* NOTE: If you extend this function, extend MSVCRT__cscanf in console.c too */
1577     int rd = 0;
1578     int nch;
1579     va_list ap;
1580     if (!*format) return 0;
1581     WARN("%p (\"%s\"): semi-stub\n", file, format);
1582     nch = MSVCRT_fgetc(file);
1583     va_start(ap, format);
1584     while (*format) {
1585         /* a whitespace character in the format string causes scanf to read,
1586          * but not store, all consecutive white-space characters in the input
1587          * up to the next non-white-space character.  One white space character
1588          * in the input matches any number (including zero) and combination of
1589          * white-space characters in the input. */
1590         if (isspace(*format)) {
1591             /* skip whitespace */
1592             while ((nch!=MSVCRT_EOF) && isspace(nch))
1593                 nch = MSVCRT_fgetc(file);
1594         }
1595         /* a format specification causes scanf to read and convert characters
1596          * in the input into values of a specified type.  The value is assigned
1597          * to an argument in the argument list.  Format specifications have
1598          * the form %[*][width][{h | l | I64 | L}]type */
1599         /* FIXME: unimplemented: h/l/I64/L modifiers and some type specs. */
1600         else if (*format == '%') {
1601             int st = 0; int suppress = 0; int width = 0;
1602             int base, number_signed;
1603             format++;
1604             /* look for leading asterisk, which means 'suppress assignment of
1605              * this field'. */
1606             if (*format=='*') {
1607                 format++;
1608                 suppress=1;
1609             }
1610             /* look for width specification */
1611             while (isdigit(*format)) {
1612                 width*=10;
1613                 width+=*format++ - '0';
1614             }
1615             if (width==0) width=-1; /* no width spec seen */
1616             switch(*format) {
1617             case '%': /* read a percent symbol */
1618                 if (nch!='%') break;
1619                 nch = MSVCRT_fgetc(file);
1620                 break;
1621             case 'x':
1622             case 'X': /* hexadecimal integer. */
1623                 base = 16; number_signed = 0;
1624                 goto number;
1625             case 'o': /* octal integer */
1626                 base = 8; number_signed = 0;
1627                 goto number;
1628             case 'u': /* unsigned decimal integer */
1629                 base = 10; number_signed = 0;
1630                 goto number;
1631             case 'd': /* signed decimal integer */
1632                 base = 10; number_signed = 1;
1633                 goto number;
1634             case 'i': /* generic integer */
1635                 base = 0; number_signed = 1;
1636             number: {
1637                     /* read an integer */
1638                     int*val = suppress ? NULL : va_arg(ap, int*);
1639                     int cur = 0; int negative = 0; int seendigit=0;
1640                     /* skip initial whitespace */
1641                     while ((nch!=MSVCRT_EOF) && isspace(nch))
1642                         nch = MSVCRT_fgetc(file);
1643                     /* get sign */
1644                     if (number_signed && (nch == '-' || nch == '+')) {
1645                         negative = (nch=='-');
1646                         nch = MSVCRT_fgetc(file);
1647                         if (width>0) width--;
1648                     }
1649                     /* look for leading indication of base */
1650                     if (width!=0 && nch == '0') {
1651                         nch = MSVCRT_fgetc(file);
1652                         if (width>0) width--;
1653                         seendigit=1;
1654                         if (width!=0 && (nch=='x' || nch=='X')) {
1655                             if (base==0)
1656                                 base=16;
1657                             if (base==16) {
1658                                 nch = MSVCRT_fgetc(file);
1659                                 if (width>0) width--;
1660                                 seendigit=0;
1661                             }
1662                         } else if (base==0)
1663                             base = 8;
1664                     }
1665                     if (base==0)
1666                         base=10;
1667                     /* throw away leading zeros */
1668                     while (width!=0 && nch=='0') {
1669                         nch = MSVCRT_fgetc(file);
1670                         if (width>0) width--;
1671                         seendigit=1;
1672                     }
1673                     /* get first digit.  Keep working copy negative, as the
1674                      * range of negative numbers in two's complement notation
1675                      * is one larger than the range of positive numbers. */
1676                     if (width!=0 && char2digit(nch, base)!=-1) {
1677                         cur = -char2digit(nch, base);
1678                         nch = MSVCRT_fgetc(file);
1679                         if (width>0) width--;
1680                         seendigit=1;
1681                     }
1682                     /* read until no more digits */
1683                     while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
1684                         cur = cur*base + char2digit(nch, base);
1685                         nch = MSVCRT_fgetc(file);
1686                         if (width>0) width--;
1687                         seendigit=1;
1688                     }
1689                     /* negate parsed number if non-negative */
1690                     if (!negative) cur=-cur;
1691                     /* okay, done! */
1692                     if (!seendigit) break; /* not a valid number */
1693                     st = 1;
1694                     if (!suppress) *val = cur;
1695                 }
1696                 break;
1697             case 'e':
1698             case 'E':
1699             case 'f':
1700             case 'g':
1701             case 'G': { /* read a float */
1702                     float*val = suppress ? NULL : va_arg(ap, float*);
1703                     float cur = 0;
1704                     int negative = 0;
1705                     /* skip initial whitespace */
1706                     while ((nch!=MSVCRT_EOF) && isspace(nch))
1707                         nch = MSVCRT_fgetc(file);
1708                     /* get sign. */
1709                     if (nch == '-' || nch == '+') {
1710                         negative = (nch=='-');
1711                         if (width>0) width--;
1712                         if (width==0) break;
1713                         nch = MSVCRT_fgetc(file);
1714                     }
1715                     /* get first digit. */
1716                     if (!isdigit(nch)) break;
1717                     cur = (nch - '0') * (negative ? -1 : 1);
1718                     nch = MSVCRT_fgetc(file);
1719                     if (width>0) width--;
1720                     /* read until no more digits */
1721                     while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
1722                         cur = cur*10 + (nch - '0');
1723                         nch = MSVCRT_fgetc(file);
1724                         if (width>0) width--;
1725                     }
1726                     /* handle decimals */
1727                     if (width!=0 && nch == '.') {
1728                         float dec = 1;
1729                         nch = MSVCRT_fgetc(file);
1730                         if (width>0) width--;
1731                         while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
1732                             dec /= 10;
1733                             cur += dec * (nch - '0');
1734                             nch = MSVCRT_fgetc(file);
1735                             if (width>0) width--;
1736                         }
1737                     }
1738                     /* handle exponent */
1739                     if (width!=0 && (nch == 'e' || nch == 'E')) {
1740                         int exponent = 0, negexp = 0;
1741                         float expcnt;
1742                         nch = MSVCRT_fgetc(file);
1743                         if (width>0) width--;
1744                         /* possible sign on the exponent */
1745                         if (width!=0 && (nch=='+' || nch=='-')) {
1746                             negexp = (nch=='-');
1747                             nch = MSVCRT_fgetc(file);
1748                             if (width>0) width--;
1749                         }
1750                         /* exponent digits */
1751                         while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
1752                             exponent *= 10;
1753                             exponent += (nch - '0');
1754                             nch = MSVCRT_fgetc(file);
1755                             if (width>0) width--;
1756                         }
1757                         /* update 'cur' with this exponent. */
1758                         expcnt =  negexp ? .1 : 10;
1759                         while (exponent!=0) {
1760                             if (exponent&1)
1761                                 cur*=expcnt;
1762                             exponent/=2;
1763                             expcnt=expcnt*expcnt;
1764                         }
1765                     }
1766                     st = 1;
1767                     if (!suppress) *val = cur;
1768                 }
1769                 break;
1770             case 's': { /* read a word */
1771                     char*str = suppress ? NULL : va_arg(ap, char*);
1772                     char*sptr = str;
1773                     /* skip initial whitespace */
1774                     while ((nch!=MSVCRT_EOF) && isspace(nch))
1775                         nch = MSVCRT_fgetc(file);
1776                     /* read until whitespace */
1777                     while (width!=0 && (nch!=MSVCRT_EOF) && !isspace(nch)) {
1778                         if (!suppress) *sptr++ = nch;
1779                         st++;
1780                         nch = MSVCRT_fgetc(file);
1781                         if (width>0) width--;
1782                     }
1783                     /* terminate */
1784                     if (!suppress) *sptr = 0;
1785                     TRACE("read word: %s\n", str);
1786                 }
1787                 break;
1788             default: FIXME("unhandled: %%%c\n", *format);
1789                 /* From spec: "if a percent sign is followed by a character
1790                  * that has no meaning as a format-control character, that
1791                  * character and the following characters are treated as
1792                  * an ordinary sequence of characters, that is, a sequence
1793                  * of characters that must match the input.  For example,
1794                  * to specify that a percent-sign character is to be input,
1795                  * use %%."
1796                  * LEAVING AS-IS because we catch bugs better that way. */
1797             }
1798             if (st && !suppress) rd++;
1799             else break;
1800         }
1801         /* a non-white-space character causes scanf to read, but not store,
1802          * a matching non-white-space character. */
1803         else {
1804             /* check for character match */
1805             if (nch == *format)
1806                nch = MSVCRT_fgetc(file);
1807             else break;
1808         }
1809         format++;
1810     }
1811     if (nch!=MSVCRT_EOF) {
1812         FIXME("need ungetch\n");
1813     }
1814     va_end(ap);
1815     TRACE("returning %d\n", rd);
1816     return rd;
1817 }
1818
1819 /*********************************************************************
1820  *              fseek (MSVCRT.@)
1821  */
1822 int MSVCRT_fseek(MSVCRT_FILE* file, long offset, int whence)
1823 {
1824   return _lseek(file->_file,offset,whence);
1825 }
1826
1827 /*********************************************************************
1828  *              ftell (MSVCRT.@)
1829  */
1830 LONG MSVCRT_ftell(MSVCRT_FILE* file)
1831 {
1832   return _tell(file->_file);
1833 }
1834
1835 /*********************************************************************
1836  *              fwrite (MSVCRT.@)
1837  */
1838 MSVCRT_size_t MSVCRT_fwrite(const void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
1839 {
1840   int written = _write(file->_file, ptr, size * nmemb);
1841   if (written <= 0)
1842     return 0;
1843   return written / size;
1844 }
1845
1846 /*********************************************************************
1847  *              fputs (MSVCRT.@)
1848  */
1849 int MSVCRT_fputs(const char *s, MSVCRT_FILE* file)
1850 {
1851   return MSVCRT_fwrite(s,strlen(s),1,file) == 1 ? 0 : MSVCRT_EOF;
1852 }
1853
1854 /*********************************************************************
1855  *              fputws (MSVCRT.@)
1856  */
1857 int MSVCRT_fputws(const WCHAR *s, MSVCRT_FILE* file)
1858 {
1859   return MSVCRT_fwrite(s,strlenW(s),1,file) == 1 ? 0 : MSVCRT_EOF;
1860 }
1861
1862 /*********************************************************************
1863  *              getchar (MSVCRT.@)
1864  */
1865 int MSVCRT_getchar(void)
1866 {
1867   return MSVCRT_fgetc(MSVCRT_stdin);
1868 }
1869
1870 /*********************************************************************
1871  *              getc (MSVCRT.@)
1872  */
1873 int MSVCRT_getc(MSVCRT_FILE* file)
1874 {
1875   return MSVCRT_fgetc(file);
1876 }
1877
1878 /*********************************************************************
1879  *              gets (MSVCRT.@)
1880  */
1881 char *MSVCRT_gets(char *buf)
1882 {
1883   int    cc;
1884   char * buf_start = buf;
1885
1886   /* BAD, for the whole WINE process blocks... just done this way to test
1887    * windows95's ftp.exe.
1888    * JG 19/9/00: Is this still true, now we are using ReadFile?
1889    */
1890   for(cc = MSVCRT_fgetc(MSVCRT_stdin); cc != MSVCRT_EOF && cc != '\n';
1891       cc = MSVCRT_fgetc(MSVCRT_stdin))
1892   if(cc != '\r') *buf++ = (char)cc;
1893
1894   *buf = '\0';
1895
1896   TRACE("got '%s'\n", buf_start);
1897   return buf_start;
1898 }
1899
1900 /*********************************************************************
1901  *              putc (MSVCRT.@)
1902  */
1903 int MSVCRT_putc(int c, MSVCRT_FILE* file)
1904 {
1905   return MSVCRT_fputc(c, file);
1906 }
1907
1908 /*********************************************************************
1909  *              putchar (MSVCRT.@)
1910  */
1911 int MSVCRT_putchar(int c)
1912 {
1913   return MSVCRT_fputc(c, MSVCRT_stdout);
1914 }
1915
1916 /*********************************************************************
1917  *              puts (MSVCRT.@)
1918  */
1919 int MSVCRT_puts(const char *s)
1920 {
1921   int retval = MSVCRT_EOF;
1922   if (MSVCRT_fwrite(s,strlen(s),1,MSVCRT_stdout) == 1)
1923     return MSVCRT_fwrite("\n",1,1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
1924   return retval;
1925 }
1926
1927 /*********************************************************************
1928  *              _putws (MSVCRT.@)
1929  */
1930 int _putws(const WCHAR *s)
1931 {
1932   static const WCHAR nl = (WCHAR)L'\n';
1933   if (MSVCRT_fwrite(s,strlenW(s),1,MSVCRT_stdout) == 1)
1934     return MSVCRT_fwrite(&nl,sizeof(nl),1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
1935   return MSVCRT_EOF;
1936 }
1937
1938 /*********************************************************************
1939  *              remove (MSVCRT.@)
1940  */
1941 int MSVCRT_remove(const char *path)
1942 {
1943   TRACE("(%s)\n",path);
1944   if (DeleteFileA(path))
1945     return 0;
1946   TRACE(":failed (%ld)\n",GetLastError());
1947   MSVCRT__set_errno(GetLastError());
1948   return -1;
1949 }
1950
1951 /*********************************************************************
1952  *              _wremove (MSVCRT.@)
1953  */
1954 int _wremove(const WCHAR *path)
1955 {
1956   TRACE("(%s)\n",debugstr_w(path));
1957   if (DeleteFileW(path))
1958     return 0;
1959   TRACE(":failed (%ld)\n",GetLastError());
1960   MSVCRT__set_errno(GetLastError());
1961   return -1;
1962 }
1963
1964 /*********************************************************************
1965  *              scanf (MSVCRT.@)
1966  */
1967 int MSVCRT_scanf(const char *format, ...)
1968 {
1969   va_list valist;
1970   int res;
1971
1972   va_start(valist, format);
1973   res = MSVCRT_fscanf(MSVCRT_stdin, format, valist);
1974   va_end(valist);
1975   return res;
1976 }
1977
1978 /*********************************************************************
1979  *              rename (MSVCRT.@)
1980  */
1981 int MSVCRT_rename(const char *oldpath,const char *newpath)
1982 {
1983   TRACE(":from %s to %s\n",oldpath,newpath);
1984   if (MoveFileExA(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
1985     return 0;
1986   TRACE(":failed (%ld)\n",GetLastError());
1987   MSVCRT__set_errno(GetLastError());
1988   return -1;
1989 }
1990
1991 /*********************************************************************
1992  *              _wrename (MSVCRT.@)
1993  */
1994 int _wrename(const WCHAR *oldpath,const WCHAR *newpath)
1995 {
1996   TRACE(":from %s to %s\n",debugstr_w(oldpath),debugstr_w(newpath));
1997   if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
1998     return 0;
1999   TRACE(":failed (%ld)\n",GetLastError());
2000   MSVCRT__set_errno(GetLastError());
2001   return -1;
2002 }
2003
2004 /*********************************************************************
2005  *              setvbuf (MSVCRT.@)
2006  */
2007 int MSVCRT_setvbuf(MSVCRT_FILE* file, char *buf, int mode, MSVCRT_size_t size)
2008 {
2009   FIXME("(%p,%p,%d,%d)stub\n",file, buf, mode, size);
2010   return -1;
2011 }
2012
2013 /*********************************************************************
2014  *              setbuf (MSVCRT.@)
2015  */
2016 void MSVCRT_setbuf(MSVCRT_FILE* file, char *buf)
2017 {
2018   MSVCRT_setvbuf(file, buf, buf ? MSVCRT__IOFBF : MSVCRT__IONBF, BUFSIZ);
2019 }
2020
2021 /*********************************************************************
2022  *              tmpnam (MSVCRT.@)
2023  */
2024 char *MSVCRT_tmpnam(char *s)
2025 {
2026   char tmpbuf[MAX_PATH];
2027   char* prefix = "TMP";
2028   if (!GetTempPathA(MAX_PATH,tmpbuf) ||
2029       !GetTempFileNameA(tmpbuf,prefix,0,MSVCRT_tmpname))
2030   {
2031     TRACE(":failed-last error (%ld)\n",GetLastError());
2032     return NULL;
2033   }
2034   TRACE(":got tmpnam %s\n",MSVCRT_tmpname);
2035   s = MSVCRT_tmpname;
2036   return s;
2037 }
2038
2039 /*********************************************************************
2040  *              tmpfile (MSVCRT.@)
2041  */
2042 MSVCRT_FILE* MSVCRT_tmpfile(void)
2043 {
2044   char *filename = MSVCRT_tmpnam(NULL);
2045   int fd;
2046   fd = _open(filename, _O_CREAT | _O_BINARY | _O_RDWR | _O_TEMPORARY);
2047   if (fd != -1)
2048     return msvcrt_alloc_fp(fd);
2049   return NULL;
2050 }
2051
2052 /*********************************************************************
2053  *              vfprintf (MSVCRT.@)
2054  */
2055 int MSVCRT_vfprintf(MSVCRT_FILE* file, const char *format, va_list valist)
2056 {
2057   char buf[2048], *mem = buf;
2058   int written, resize = sizeof(buf), retval;
2059   /* There are two conventions for vsnprintf failing:
2060    * Return -1 if we truncated, or
2061    * Return the number of bytes that would have been written
2062    * The code below handles both cases
2063    */
2064   while ((written = vsnprintf(mem, resize, format, valist)) == -1 ||
2065           written > resize)
2066   {
2067     resize = (written == -1 ? resize * 2 : written + 1);
2068     if (mem != buf)
2069       MSVCRT_free (mem);
2070     if (!(mem = (char *)MSVCRT_malloc(resize)))
2071       return MSVCRT_EOF;
2072   }
2073   retval = MSVCRT_fwrite(mem, 1, written, file);
2074   if (mem != buf)
2075     MSVCRT_free (mem);
2076   return retval;
2077 }
2078
2079 /*********************************************************************
2080  *              vfwprintf (MSVCRT.@)
2081  */
2082 int MSVCRT_vfwprintf(MSVCRT_FILE* file, const WCHAR *format, va_list valist)
2083 {
2084   WCHAR buf[2048], *mem = buf;
2085   int written, resize = sizeof(buf) / sizeof(WCHAR), retval;
2086   /* See vfprintf comments */
2087   while ((written = _vsnwprintf(mem, resize, format, valist)) == -1 ||
2088           written > resize)
2089   {
2090     resize = (written == -1 ? resize * 2 : written + sizeof(WCHAR));
2091     if (mem != buf)
2092       MSVCRT_free (mem);
2093     if (!(mem = (WCHAR *)MSVCRT_malloc(resize)))
2094       return MSVCRT_EOF;
2095   }
2096   retval = MSVCRT_fwrite(mem, 1, written * sizeof (WCHAR), file);
2097   if (mem != buf)
2098     MSVCRT_free (mem);
2099   return retval;
2100 }
2101
2102 /*********************************************************************
2103  *              vprintf (MSVCRT.@)
2104  */
2105 int MSVCRT_vprintf(const char *format, va_list valist)
2106 {
2107   return MSVCRT_vfprintf(MSVCRT_stdout,format,valist);
2108 }
2109
2110 /*********************************************************************
2111  *              vwprintf (MSVCRT.@)
2112  */
2113 int MSVCRT_vwprintf(const WCHAR *format, va_list valist)
2114 {
2115   return MSVCRT_vfwprintf(MSVCRT_stdout,format,valist);
2116 }
2117
2118 /*********************************************************************
2119  *              fprintf (MSVCRT.@)
2120  */
2121 int MSVCRT_fprintf(MSVCRT_FILE* file, const char *format, ...)
2122 {
2123     va_list valist;
2124     int res;
2125     va_start(valist, format);
2126     res = MSVCRT_vfprintf(file, format, valist);
2127     va_end(valist);
2128     return res;
2129 }
2130
2131 /*********************************************************************
2132  *              fwprintf (MSVCRT.@)
2133  */
2134 int MSVCRT_fwprintf(MSVCRT_FILE* file, const WCHAR *format, ...)
2135 {
2136     va_list valist;
2137     int res;
2138     va_start(valist, format);
2139     res = MSVCRT_vfwprintf(file, format, valist);
2140     va_end(valist);
2141     return res;
2142 }
2143
2144 /*********************************************************************
2145  *              printf (MSVCRT.@)
2146  */
2147 int MSVCRT_printf(const char *format, ...)
2148 {
2149     va_list valist;
2150     int res;
2151     va_start(valist, format);
2152     res = MSVCRT_vfprintf(MSVCRT_stdout, format, valist);
2153     va_end(valist);
2154     return res;
2155 }
2156
2157 /*********************************************************************
2158  *              wprintf (MSVCRT.@)
2159  */
2160 int MSVCRT_wprintf(const WCHAR *format, ...)
2161 {
2162     va_list valist;
2163     int res;
2164     va_start(valist, format);
2165     res = MSVCRT_vwprintf(format, valist);
2166     va_end(valist);
2167     return res;
2168 }