wintrust: Close file handle on error loading a message from it.
[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  * Copyright 2004 Eric Pouech
9  * Copyright 2004 Juan Lang
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  *
25  * TODO
26  * Use the file flag hints O_SEQUENTIAL, O_RANDOM, O_SHORT_LIVED
27  */
28
29 #include "config.h"
30 #include "wine/port.h"
31
32 #include <time.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #ifdef HAVE_UNISTD_H
36 # include <unistd.h>
37 #endif
38 #include <sys/types.h>
39
40 #include "windef.h"
41 #include "winbase.h"
42 #include "winternl.h"
43 #include "msvcrt.h"
44
45 #include "wine/unicode.h"
46
47 #include "wine/debug.h"
48
49 WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
50
51 /* for stat mode, permissions apply to all,owner and group */
52 #define ALL_S_IREAD  (MSVCRT__S_IREAD  | (MSVCRT__S_IREAD  >> 3) | (MSVCRT__S_IREAD  >> 6))
53 #define ALL_S_IWRITE (MSVCRT__S_IWRITE | (MSVCRT__S_IWRITE >> 3) | (MSVCRT__S_IWRITE >> 6))
54 #define ALL_S_IEXEC  (MSVCRT__S_IEXEC  | (MSVCRT__S_IEXEC  >> 3) | (MSVCRT__S_IEXEC  >> 6))
55
56 /* _access() bit flags FIXME: incomplete */
57 #define MSVCRT_W_OK      0x02
58
59 /* values for wxflag in file descriptor */
60 #define WX_OPEN           0x01
61 #define WX_ATEOF          0x02
62 #define WX_READEOF        0x04  /* like ATEOF, but for underlying file rather than buffer */
63 #define WX_READCR         0x08  /* underlying file is at \r */
64 #define WX_DONTINHERIT    0x10
65 #define WX_APPEND         0x20
66 #define WX_TEXT           0x80
67
68 /* FIXME: this should be allocated dynamically */
69 #define MSVCRT_MAX_FILES 2048
70
71 typedef struct {
72     HANDLE              handle;
73     unsigned char       wxflag;
74     DWORD               unkn[7]; /* critical section and init flag */       
75 } ioinfo;
76
77 static ioinfo MSVCRT_fdesc[MSVCRT_MAX_FILES];
78
79 MSVCRT_FILE MSVCRT__iob[3] = { { 0 } };
80
81 static int MSVCRT_fdstart = 3; /* first unallocated fd */
82 static int MSVCRT_fdend = 3; /* highest allocated fd */
83
84 static MSVCRT_FILE* MSVCRT_fstreams[2048];
85 static int   MSVCRT_stream_idx;
86
87 /* INTERNAL: process umask */
88 static int MSVCRT_umask = 0;
89
90 /* INTERNAL: Static buffer for temp file name */
91 static char MSVCRT_tmpname[MAX_PATH];
92
93 static const unsigned int EXE = 'e' << 16 | 'x' << 8 | 'e';
94 static const unsigned int BAT = 'b' << 16 | 'a' << 8 | 't';
95 static const unsigned int CMD = 'c' << 16 | 'm' << 8 | 'd';
96 static const unsigned int COM = 'c' << 16 | 'o' << 8 | 'm';
97
98 #define TOUL(x) (ULONGLONG)(x)
99 static const ULONGLONG WCEXE = TOUL('e') << 32 | TOUL('x') << 16 | TOUL('e');
100 static const ULONGLONG WCBAT = TOUL('b') << 32 | TOUL('a') << 16 | TOUL('t');
101 static const ULONGLONG WCCMD = TOUL('c') << 32 | TOUL('m') << 16 | TOUL('d');
102 static const ULONGLONG WCCOM = TOUL('c') << 32 | TOUL('o') << 16 | TOUL('m');
103
104 /* This critical section protects the tables MSVCRT_fdesc and MSVCRT_fstreams,
105  * and their related indexes, MSVCRT_fdstart, MSVCRT_fdend,
106  * and MSVCRT_stream_idx, from race conditions.
107  * It doesn't protect against race conditions manipulating the underlying files
108  * or flags; doing so would probably be better accomplished with per-file
109  * protection, rather than locking the whole table for every change.
110  */
111 static CRITICAL_SECTION MSVCRT_file_cs;
112 #define LOCK_FILES()    do { EnterCriticalSection(&MSVCRT_file_cs); } while (0)
113 #define UNLOCK_FILES()  do { LeaveCriticalSection(&MSVCRT_file_cs); } while (0)
114
115 static void msvcrt_stat64_to_stat(const struct MSVCRT__stat64 *buf64, struct MSVCRT__stat *buf)
116 {
117     buf->st_dev   = buf64->st_dev;
118     buf->st_ino   = buf64->st_ino;
119     buf->st_mode  = buf64->st_mode;
120     buf->st_nlink = buf64->st_nlink;
121     buf->st_uid   = buf64->st_uid;
122     buf->st_gid   = buf64->st_gid;
123     buf->st_rdev  = buf64->st_rdev;
124     buf->st_size  = buf64->st_size;
125     buf->st_atime = buf64->st_atime;
126     buf->st_mtime = buf64->st_mtime;
127     buf->st_ctime = buf64->st_ctime;
128 }
129
130 static void msvcrt_stat64_to_stati64(const struct MSVCRT__stat64 *buf64, struct MSVCRT__stati64 *buf)
131 {
132     buf->st_dev   = buf64->st_dev;
133     buf->st_ino   = buf64->st_ino;
134     buf->st_mode  = buf64->st_mode;
135     buf->st_nlink = buf64->st_nlink;
136     buf->st_uid   = buf64->st_uid;
137     buf->st_gid   = buf64->st_gid;
138     buf->st_rdev  = buf64->st_rdev;
139     buf->st_size  = buf64->st_size;
140     buf->st_atime = buf64->st_atime;
141     buf->st_mtime = buf64->st_mtime;
142     buf->st_ctime = buf64->st_ctime;
143 }
144
145 static void time_to_filetime( MSVCRT___time64_t time, FILETIME *ft )
146 {
147     /* 1601 to 1970 is 369 years plus 89 leap days */
148     static const __int64 secs_1601_to_1970 = ((369 * 365 + 89) * (__int64)86400);
149
150     __int64 ticks = (time + secs_1601_to_1970) * 10000000;
151     ft->dwHighDateTime = ticks >> 32;
152     ft->dwLowDateTime = ticks;
153 }
154
155 static inline BOOL msvcrt_is_valid_fd(int fd)
156 {
157   return fd >= 0 && fd < MSVCRT_fdend && (MSVCRT_fdesc[fd].wxflag & WX_OPEN);
158 }
159
160 /* INTERNAL: Get the HANDLE for a fd
161  * This doesn't lock the table, because a failure will result in
162  * INVALID_HANDLE_VALUE being returned, which should be handled correctly.  If
163  * it returns a valid handle which is about to be closed, a subsequent call
164  * will fail, most likely in a sane way.
165  */
166 static HANDLE msvcrt_fdtoh(int fd)
167 {
168   if (!msvcrt_is_valid_fd(fd))
169   {
170     WARN(":fd (%d) - no handle!\n",fd);
171     *MSVCRT___doserrno() = 0;
172     *MSVCRT__errno() = MSVCRT_EBADF;
173     return INVALID_HANDLE_VALUE;
174   }
175   if (MSVCRT_fdesc[fd].handle == INVALID_HANDLE_VALUE) FIXME("wtf\n");
176   return MSVCRT_fdesc[fd].handle;
177 }
178
179 /* INTERNAL: free a file entry fd */
180 static void msvcrt_free_fd(int fd)
181 {
182   HANDLE old_handle;
183
184   LOCK_FILES();
185   old_handle = MSVCRT_fdesc[fd].handle;
186   MSVCRT_fdesc[fd].handle = INVALID_HANDLE_VALUE;
187   MSVCRT_fdesc[fd].wxflag = 0;
188   TRACE(":fd (%d) freed\n",fd);
189   if (fd < 3) /* don't use 0,1,2 for user files */
190   {
191     switch (fd)
192     {
193     case 0:
194         if (GetStdHandle(STD_INPUT_HANDLE) == old_handle) SetStdHandle(STD_INPUT_HANDLE, 0);
195         break;
196     case 1:
197         if (GetStdHandle(STD_OUTPUT_HANDLE) == old_handle) SetStdHandle(STD_OUTPUT_HANDLE, 0);
198         break;
199     case 2:
200         if (GetStdHandle(STD_ERROR_HANDLE) == old_handle) SetStdHandle(STD_ERROR_HANDLE, 0);
201         break;
202     }
203   }
204   else
205   {
206     if (fd == MSVCRT_fdend - 1)
207       MSVCRT_fdend--;
208     if (fd < MSVCRT_fdstart)
209       MSVCRT_fdstart = fd;
210   }
211   UNLOCK_FILES();
212 }
213
214 /* INTERNAL: Allocate an fd slot from a Win32 HANDLE, starting from fd */
215 /* caller must hold the files lock */
216 static int msvcrt_alloc_fd_from(HANDLE hand, int flag, int fd)
217 {
218   if (fd >= MSVCRT_MAX_FILES)
219   {
220     WARN(":files exhausted!\n");
221     return -1;
222   }
223   MSVCRT_fdesc[fd].handle = hand;
224   MSVCRT_fdesc[fd].wxflag = WX_OPEN | (flag & (WX_DONTINHERIT | WX_APPEND | WX_TEXT));
225
226   /* locate next free slot */
227   if (fd == MSVCRT_fdstart && fd == MSVCRT_fdend)
228     MSVCRT_fdstart = MSVCRT_fdend + 1;
229   else
230     while (MSVCRT_fdstart < MSVCRT_fdend &&
231      MSVCRT_fdesc[MSVCRT_fdstart].handle != INVALID_HANDLE_VALUE)
232       MSVCRT_fdstart++;
233   /* update last fd in use */
234   if (fd >= MSVCRT_fdend)
235     MSVCRT_fdend = fd + 1;
236   TRACE("fdstart is %d, fdend is %d\n", MSVCRT_fdstart, MSVCRT_fdend);
237
238   switch (fd)
239   {
240   case 0: SetStdHandle(STD_INPUT_HANDLE,  hand); break;
241   case 1: SetStdHandle(STD_OUTPUT_HANDLE, hand); break;
242   case 2: SetStdHandle(STD_ERROR_HANDLE,  hand); break;
243   }
244
245   return fd;
246 }
247
248 /* INTERNAL: Allocate an fd slot from a Win32 HANDLE */
249 static int msvcrt_alloc_fd(HANDLE hand, int flag)
250 {
251   int ret;
252
253   LOCK_FILES();
254   TRACE(":handle (%p) allocating fd (%d)\n",hand,MSVCRT_fdstart);
255   ret = msvcrt_alloc_fd_from(hand, flag, MSVCRT_fdstart);
256   UNLOCK_FILES();
257   return ret;
258 }
259
260 /* INTERNAL: Allocate a FILE* for an fd slot */
261 /* caller must hold the files lock */
262 static MSVCRT_FILE* msvcrt_alloc_fp(void)
263 {
264   unsigned int i;
265
266   for (i = 3; i < sizeof(MSVCRT_fstreams) / sizeof(MSVCRT_fstreams[0]); i++)
267   {
268     if (!MSVCRT_fstreams[i] || MSVCRT_fstreams[i]->_flag == 0)
269     {
270       if (!MSVCRT_fstreams[i])
271       {
272         if (!(MSVCRT_fstreams[i] = MSVCRT_calloc(sizeof(MSVCRT_FILE),1)))
273           return NULL;
274         if (i == MSVCRT_stream_idx) MSVCRT_stream_idx++;
275       }
276       return MSVCRT_fstreams[i];
277     }
278   }
279   return NULL;
280 }
281
282 /* INTERNAL: initialize a FILE* from an open fd */
283 static int msvcrt_init_fp(MSVCRT_FILE* file, int fd, unsigned stream_flags)
284 {
285   TRACE(":fd (%d) allocating FILE*\n",fd);
286   if (!msvcrt_is_valid_fd(fd))
287   {
288     WARN(":invalid fd %d\n",fd);
289     *MSVCRT___doserrno() = 0;
290     *MSVCRT__errno() = MSVCRT_EBADF;
291     return -1;
292   }
293   memset(file, 0, sizeof(*file));
294   file->_file = fd;
295   file->_flag = stream_flags;
296
297   TRACE(":got FILE* (%p)\n",file);
298   return 0;
299 }
300
301 /* INTERNAL: Create an inheritance data block (for spawned process)
302  * The inheritance block is made of:
303  *      00      int     nb of file descriptor (NBFD)
304  *      04      char    file flags (wxflag): repeated for each fd
305  *      4+NBFD  HANDLE  file handle: repeated for each fd
306  */
307 unsigned msvcrt_create_io_inherit_block(WORD *size, BYTE **block)
308 {
309   int         fd;
310   char*       wxflag_ptr;
311   HANDLE*     handle_ptr;
312
313   *size = sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * MSVCRT_fdend;
314   *block = MSVCRT_calloc(*size, 1);
315   if (!*block)
316   {
317     *size = 0;
318     return FALSE;
319   }
320   wxflag_ptr = (char*)*block + sizeof(unsigned);
321   handle_ptr = (HANDLE*)(wxflag_ptr + MSVCRT_fdend * sizeof(char));
322
323   *(unsigned*)*block = MSVCRT_fdend;
324   for (fd = 0; fd < MSVCRT_fdend; fd++)
325   {
326     /* to be inherited, we need it to be open, and that DONTINHERIT isn't set */
327     if ((MSVCRT_fdesc[fd].wxflag & (WX_OPEN | WX_DONTINHERIT)) == WX_OPEN)
328     {
329       *wxflag_ptr = MSVCRT_fdesc[fd].wxflag;
330       *handle_ptr = MSVCRT_fdesc[fd].handle;
331     }
332     else
333     {
334       *wxflag_ptr = 0;
335       *handle_ptr = INVALID_HANDLE_VALUE;
336     }
337     wxflag_ptr++; handle_ptr++;
338   } 
339   return TRUE;
340 }
341
342 /* INTERNAL: Set up all file descriptors, 
343  * as well as default streams (stdin, stderr and stdout) 
344  */
345 void msvcrt_init_io(void)
346 {
347   STARTUPINFOA  si;
348   int           i;
349
350   InitializeCriticalSection(&MSVCRT_file_cs);
351   MSVCRT_file_cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": MSVCRT_file_cs");
352   GetStartupInfoA(&si);
353   if (si.cbReserved2 >= sizeof(unsigned int) && si.lpReserved2 != NULL)
354   {
355     BYTE*       wxflag_ptr;
356     HANDLE*     handle_ptr;
357     unsigned int count;
358
359     count = *(unsigned*)si.lpReserved2;
360     wxflag_ptr = si.lpReserved2 + sizeof(unsigned);
361     handle_ptr = (HANDLE*)(wxflag_ptr + count);
362
363     count = min(count, (si.cbReserved2 - sizeof(unsigned)) / (sizeof(HANDLE) + 1));
364     count = min(count, sizeof(MSVCRT_fdesc) / sizeof(MSVCRT_fdesc[0]));
365     for (i = 0; i < count; i++)
366     {
367       if ((*wxflag_ptr & WX_OPEN) && *handle_ptr != INVALID_HANDLE_VALUE)
368       {
369         MSVCRT_fdesc[i].wxflag  = *wxflag_ptr;
370         MSVCRT_fdesc[i].handle = *handle_ptr;
371       }
372       else
373       {
374         MSVCRT_fdesc[i].wxflag  = 0;
375         MSVCRT_fdesc[i].handle = INVALID_HANDLE_VALUE;
376       }
377       wxflag_ptr++; handle_ptr++;
378     }
379     MSVCRT_fdend = max( 3, count );
380     for (MSVCRT_fdstart = 3; MSVCRT_fdstart < MSVCRT_fdend; MSVCRT_fdstart++)
381         if (MSVCRT_fdesc[MSVCRT_fdstart].handle == INVALID_HANDLE_VALUE) break;
382   }
383
384   if (!(MSVCRT_fdesc[0].wxflag & WX_OPEN) || MSVCRT_fdesc[0].handle == INVALID_HANDLE_VALUE)
385   {
386       HANDLE std = GetStdHandle(STD_INPUT_HANDLE);
387       if (std != INVALID_HANDLE_VALUE && DuplicateHandle(GetCurrentProcess(), std,
388                                                          GetCurrentProcess(), &MSVCRT_fdesc[0].handle,
389                                                          0, TRUE, DUPLICATE_SAME_ACCESS))
390           MSVCRT_fdesc[0].wxflag = WX_OPEN | WX_TEXT;
391   }
392   if (!(MSVCRT_fdesc[1].wxflag & WX_OPEN) || MSVCRT_fdesc[1].handle == INVALID_HANDLE_VALUE)
393   {
394       HANDLE std = GetStdHandle(STD_OUTPUT_HANDLE);
395       if (std != INVALID_HANDLE_VALUE && DuplicateHandle(GetCurrentProcess(), std,
396                                                          GetCurrentProcess(), &MSVCRT_fdesc[1].handle,
397                                                          0, TRUE, DUPLICATE_SAME_ACCESS))
398           MSVCRT_fdesc[1].wxflag = WX_OPEN | WX_TEXT;
399   }
400   if (!(MSVCRT_fdesc[2].wxflag & WX_OPEN) || MSVCRT_fdesc[2].handle == INVALID_HANDLE_VALUE)
401   {
402       HANDLE std = GetStdHandle(STD_ERROR_HANDLE);
403       if (std != INVALID_HANDLE_VALUE && DuplicateHandle(GetCurrentProcess(), std,
404                                                          GetCurrentProcess(), &MSVCRT_fdesc[2].handle,
405                                                          0, TRUE, DUPLICATE_SAME_ACCESS))
406           MSVCRT_fdesc[2].wxflag = WX_OPEN | WX_TEXT;
407   }
408
409   TRACE(":handles (%p)(%p)(%p)\n",MSVCRT_fdesc[0].handle,
410         MSVCRT_fdesc[1].handle,MSVCRT_fdesc[2].handle);
411
412   memset(MSVCRT__iob,0,3*sizeof(MSVCRT_FILE));
413   for (i = 0; i < 3; i++)
414   {
415     /* FILE structs for stdin/out/err are static and never deleted */
416     MSVCRT_fstreams[i] = &MSVCRT__iob[i];
417     MSVCRT__iob[i]._file = i;
418     MSVCRT__iob[i]._tmpfname = NULL;
419     MSVCRT__iob[i]._flag = (i == 0) ? MSVCRT__IOREAD : MSVCRT__IOWRT;
420   }
421   MSVCRT_stream_idx = 3;
422 }
423
424 /* INTERNAL: Flush stdio file buffer */
425 static int msvcrt_flush_buffer(MSVCRT_FILE* file)
426 {
427   if(file->_bufsiz) {
428         int cnt=file->_ptr-file->_base;
429         if(cnt>0 && MSVCRT__write(file->_file, file->_base, cnt) != cnt) {
430             file->_flag |= MSVCRT__IOERR;
431             return MSVCRT_EOF;
432         }
433         file->_ptr=file->_base;
434         file->_cnt=file->_bufsiz;
435   }
436   return 0;
437 }
438
439 /* INTERNAL: Allocate stdio file buffer */
440 static void msvcrt_alloc_buffer(MSVCRT_FILE* file)
441 {
442         file->_base = MSVCRT_calloc(MSVCRT_BUFSIZ,1);
443         if(file->_base) {
444                 file->_bufsiz = MSVCRT_BUFSIZ;
445                 file->_flag |= MSVCRT__IOMYBUF;
446         } else {
447                 file->_base = (char*)(&file->_charbuf);
448                 /* put here 2 ??? */
449                 file->_bufsiz = sizeof(file->_charbuf);
450         }
451         file->_ptr = file->_base;
452         file->_cnt = 0;
453 }
454
455 /* INTERNAL: Convert integer to base32 string (0-9a-v), 0 becomes "" */
456 static void msvcrt_int_to_base32(int num, char *str)
457 {
458   char *p;
459   int n = num;
460   int digits = 0;
461
462   while (n != 0)
463   {
464     n >>= 5;
465     digits++;
466   }
467   p = str + digits;
468   *p = 0;
469   while (--p >= str)
470   {
471     *p = (num & 31) + '0';
472     if (*p > '9')
473       *p += ('a' - '0' - 10);
474     num >>= 5;
475   }
476 }
477
478 /*********************************************************************
479  *              __iob_func(MSVCRT.@)
480  */
481 MSVCRT_FILE * CDECL MSVCRT___iob_func(void)
482 {
483  return &MSVCRT__iob[0];
484 }
485
486 /*********************************************************************
487  *              _access (MSVCRT.@)
488  */
489 int CDECL MSVCRT__access(const char *filename, int mode)
490 {
491   DWORD attr = GetFileAttributesA(filename);
492
493   TRACE("(%s,%d) %d\n",filename,mode,attr);
494
495   if (!filename || attr == INVALID_FILE_ATTRIBUTES)
496   {
497     msvcrt_set_errno(GetLastError());
498     return -1;
499   }
500   if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
501   {
502     msvcrt_set_errno(ERROR_ACCESS_DENIED);
503     return -1;
504   }
505   return 0;
506 }
507
508 /*********************************************************************
509  *              _waccess (MSVCRT.@)
510  */
511 int CDECL _waccess(const MSVCRT_wchar_t *filename, int mode)
512 {
513   DWORD attr = GetFileAttributesW(filename);
514
515   TRACE("(%s,%d) %d\n",debugstr_w(filename),mode,attr);
516
517   if (!filename || attr == INVALID_FILE_ATTRIBUTES)
518   {
519     msvcrt_set_errno(GetLastError());
520     return -1;
521   }
522   if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
523   {
524     msvcrt_set_errno(ERROR_ACCESS_DENIED);
525     return -1;
526   }
527   return 0;
528 }
529
530 /*********************************************************************
531  *              _chmod (MSVCRT.@)
532  */
533 int CDECL MSVCRT__chmod(const char *path, int flags)
534 {
535   DWORD oldFlags = GetFileAttributesA(path);
536
537   if (oldFlags != INVALID_FILE_ATTRIBUTES)
538   {
539     DWORD newFlags = (flags & MSVCRT__S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
540       oldFlags | FILE_ATTRIBUTE_READONLY;
541
542     if (newFlags == oldFlags || SetFileAttributesA(path, newFlags))
543       return 0;
544   }
545   msvcrt_set_errno(GetLastError());
546   return -1;
547 }
548
549 /*********************************************************************
550  *              _wchmod (MSVCRT.@)
551  */
552 int CDECL _wchmod(const MSVCRT_wchar_t *path, int flags)
553 {
554   DWORD oldFlags = GetFileAttributesW(path);
555
556   if (oldFlags != INVALID_FILE_ATTRIBUTES)
557   {
558     DWORD newFlags = (flags & MSVCRT__S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
559       oldFlags | FILE_ATTRIBUTE_READONLY;
560
561     if (newFlags == oldFlags || SetFileAttributesW(path, newFlags))
562       return 0;
563   }
564   msvcrt_set_errno(GetLastError());
565   return -1;
566 }
567
568 /*********************************************************************
569  *              _unlink (MSVCRT.@)
570  */
571 int CDECL MSVCRT__unlink(const char *path)
572 {
573   TRACE("%s\n",debugstr_a(path));
574   if(DeleteFileA(path))
575     return 0;
576   TRACE("failed (%d)\n",GetLastError());
577   msvcrt_set_errno(GetLastError());
578   return -1;
579 }
580
581 /*********************************************************************
582  *              _wunlink (MSVCRT.@)
583  */
584 int CDECL _wunlink(const MSVCRT_wchar_t *path)
585 {
586   TRACE("(%s)\n",debugstr_w(path));
587   if(DeleteFileW(path))
588     return 0;
589   TRACE("failed (%d)\n",GetLastError());
590   msvcrt_set_errno(GetLastError());
591   return -1;
592 }
593
594 /* _flushall calls MSVCRT_fflush which calls _flushall */
595 int CDECL MSVCRT_fflush(MSVCRT_FILE* file);
596
597 /*********************************************************************
598  *              _flushall (MSVCRT.@)
599  */
600 int CDECL _flushall(void)
601 {
602   int i, num_flushed = 0;
603
604   LOCK_FILES();
605   for (i = 3; i < MSVCRT_stream_idx; i++)
606     if (MSVCRT_fstreams[i] && MSVCRT_fstreams[i]->_flag)
607     {
608 #if 0
609       /* FIXME: flush, do not commit */
610       if (_commit(i) == -1)
611         if (MSVCRT_fstreams[i])
612           MSVCRT_fstreams[i]->_flag |= MSVCRT__IOERR;
613 #endif
614       if(MSVCRT_fstreams[i]->_flag & MSVCRT__IOWRT) {
615         MSVCRT_fflush(MSVCRT_fstreams[i]);
616         num_flushed++;
617       }
618     }
619   UNLOCK_FILES();
620
621   TRACE(":flushed (%d) handles\n",num_flushed);
622   return num_flushed;
623 }
624
625 /*********************************************************************
626  *              fflush (MSVCRT.@)
627  */
628 int CDECL MSVCRT_fflush(MSVCRT_FILE* file)
629 {
630   if(!file) {
631         _flushall();
632   } else if(file->_flag & MSVCRT__IOWRT) {
633         int res=msvcrt_flush_buffer(file);
634         return res;
635   }
636   return 0;
637 }
638
639 /*********************************************************************
640  *              _close (MSVCRT.@)
641  */
642 int CDECL MSVCRT__close(int fd)
643 {
644   HANDLE hand;
645   int ret;
646
647   LOCK_FILES();
648   hand = msvcrt_fdtoh(fd);
649   TRACE(":fd (%d) handle (%p)\n",fd,hand);
650   if (hand == INVALID_HANDLE_VALUE)
651     ret = -1;
652   else if (!CloseHandle(hand))
653   {
654     WARN(":failed-last error (%d)\n",GetLastError());
655     msvcrt_set_errno(GetLastError());
656     ret = -1;
657   }
658   else
659   {
660     msvcrt_free_fd(fd);
661     ret = 0;
662   }
663   UNLOCK_FILES();
664   TRACE(":ok\n");
665   return ret;
666 }
667
668 /*********************************************************************
669  *              _commit (MSVCRT.@)
670  */
671 int CDECL _commit(int fd)
672 {
673   HANDLE hand = msvcrt_fdtoh(fd);
674
675   TRACE(":fd (%d) handle (%p)\n",fd,hand);
676   if (hand == INVALID_HANDLE_VALUE)
677     return -1;
678
679   if (!FlushFileBuffers(hand))
680   {
681     if (GetLastError() == ERROR_INVALID_HANDLE)
682     {
683       /* FlushFileBuffers fails for console handles
684        * so we ignore this error.
685        */
686       return 0;
687     }
688     TRACE(":failed-last error (%d)\n",GetLastError());
689     msvcrt_set_errno(GetLastError());
690     return -1;
691   }
692   TRACE(":ok\n");
693   return 0;
694 }
695
696 /*********************************************************************
697  *              _dup2 (MSVCRT.@)
698  * NOTES
699  * MSDN isn't clear on this point, but the remarks for _pipe
700  * indicate file descriptors duplicated with _dup and _dup2 are always
701  * inheritable.
702  */
703 int CDECL MSVCRT__dup2(int od, int nd)
704 {
705   int ret;
706
707   TRACE("(od=%d, nd=%d)\n", od, nd);
708   LOCK_FILES();
709   if (nd < MSVCRT_MAX_FILES && nd >= 0 && msvcrt_is_valid_fd(od))
710   {
711     HANDLE handle;
712
713     if (DuplicateHandle(GetCurrentProcess(), MSVCRT_fdesc[od].handle,
714      GetCurrentProcess(), &handle, 0, TRUE, DUPLICATE_SAME_ACCESS))
715     {
716       int wxflag = MSVCRT_fdesc[od].wxflag & ~MSVCRT__O_NOINHERIT;
717
718       if (msvcrt_is_valid_fd(nd))
719         MSVCRT__close(nd);
720       ret = msvcrt_alloc_fd_from(handle, wxflag, nd);
721       if (ret == -1)
722       {
723         CloseHandle(handle);
724         *MSVCRT__errno() = MSVCRT_EMFILE;
725       }
726       else
727       {
728         /* _dup2 returns 0, not nd, on success */
729         ret = 0;
730       }
731     }
732     else
733     {
734       ret = -1;
735       msvcrt_set_errno(GetLastError());
736     }
737   }
738   else
739   {
740     *MSVCRT__errno() = MSVCRT_EBADF;
741     ret = -1;
742   }
743   UNLOCK_FILES();
744   return ret;
745 }
746
747 /*********************************************************************
748  *              _dup (MSVCRT.@)
749  */
750 int CDECL MSVCRT__dup(int od)
751 {
752   int fd, ret;
753  
754   LOCK_FILES();
755   fd = MSVCRT_fdstart;
756   if (MSVCRT__dup2(od, fd) == 0)
757     ret = fd;
758   else
759     ret = -1;
760   UNLOCK_FILES();
761   return ret;
762 }
763
764 /*********************************************************************
765  *              _eof (MSVCRT.@)
766  */
767 int CDECL _eof(int fd)
768 {
769   DWORD curpos,endpos;
770   LONG hcurpos,hendpos;
771   HANDLE hand = msvcrt_fdtoh(fd);
772
773   TRACE(":fd (%d) handle (%p)\n",fd,hand);
774
775   if (hand == INVALID_HANDLE_VALUE)
776     return -1;
777
778   if (MSVCRT_fdesc[fd].wxflag & WX_ATEOF) return TRUE;
779
780   /* Otherwise we do it the hard way */
781   hcurpos = hendpos = 0;
782   curpos = SetFilePointer(hand, 0, &hcurpos, FILE_CURRENT);
783   endpos = SetFilePointer(hand, 0, &hendpos, FILE_END);
784
785   if (curpos == endpos && hcurpos == hendpos)
786   {
787     /* FIXME: shouldn't WX_ATEOF be set here? */
788     return TRUE;
789   }
790
791   SetFilePointer(hand, curpos, &hcurpos, FILE_BEGIN);
792   return FALSE;
793 }
794
795 /*********************************************************************
796  *              _fcloseall (MSVCRT.@)
797  */
798 int CDECL MSVCRT__fcloseall(void)
799 {
800   int num_closed = 0, i;
801
802   LOCK_FILES();
803   for (i = 3; i < MSVCRT_stream_idx; i++)
804     if (MSVCRT_fstreams[i] && MSVCRT_fstreams[i]->_flag &&
805         !MSVCRT_fclose(MSVCRT_fstreams[i]))
806       num_closed++;
807   UNLOCK_FILES();
808
809   TRACE(":closed (%d) handles\n",num_closed);
810   return num_closed;
811 }
812
813 /* free everything on process exit */
814 void msvcrt_free_io(void)
815 {
816     MSVCRT__fcloseall();
817     /* The Win32 _fcloseall() function explicitly doesn't close stdin,
818      * stdout, and stderr (unlike GNU), so we need to fclose() them here
819      * or they won't get flushed.
820      */
821     MSVCRT_fclose(&MSVCRT__iob[0]);
822     MSVCRT_fclose(&MSVCRT__iob[1]);
823     MSVCRT_fclose(&MSVCRT__iob[2]);
824     MSVCRT_file_cs.DebugInfo->Spare[0] = 0;
825     DeleteCriticalSection(&MSVCRT_file_cs);
826 }
827
828 /*********************************************************************
829  *              _lseeki64 (MSVCRT.@)
830  */
831 __int64 CDECL MSVCRT__lseeki64(int fd, __int64 offset, int whence)
832 {
833   HANDLE hand = msvcrt_fdtoh(fd);
834   LARGE_INTEGER ofs, ret;
835
836   TRACE(":fd (%d) handle (%p)\n",fd,hand);
837   if (hand == INVALID_HANDLE_VALUE)
838     return -1;
839
840   if (whence < 0 || whence > 2)
841   {
842     *MSVCRT__errno() = MSVCRT_EINVAL;
843     return -1;
844   }
845
846   TRACE(":fd (%d) to %s pos %s\n",
847         fd,wine_dbgstr_longlong(offset),
848         (whence==SEEK_SET)?"SEEK_SET":
849         (whence==SEEK_CUR)?"SEEK_CUR":
850         (whence==SEEK_END)?"SEEK_END":"UNKNOWN");
851
852   ofs.QuadPart = offset;
853   if (SetFilePointerEx(hand, ofs, &ret, whence))
854   {
855     MSVCRT_fdesc[fd].wxflag &= ~(WX_ATEOF|WX_READEOF);
856     /* FIXME: What if we seek _to_ EOF - is EOF set? */
857
858     return ret.QuadPart;
859   }
860   TRACE(":error-last error (%d)\n",GetLastError());
861   msvcrt_set_errno(GetLastError());
862   return -1;
863 }
864
865 /*********************************************************************
866  *              _lseek (MSVCRT.@)
867  */
868 LONG CDECL MSVCRT__lseek(int fd, LONG offset, int whence)
869 {
870     return MSVCRT__lseeki64(fd, offset, whence);
871 }
872
873 /*********************************************************************
874  *              _locking (MSVCRT.@)
875  *
876  * This is untested; the underlying LockFile doesn't work yet.
877  */
878 int CDECL MSVCRT__locking(int fd, int mode, LONG nbytes)
879 {
880   BOOL ret;
881   DWORD cur_locn;
882   HANDLE hand = msvcrt_fdtoh(fd);
883
884   TRACE(":fd (%d) handle (%p)\n",fd,hand);
885   if (hand == INVALID_HANDLE_VALUE)
886     return -1;
887
888   if (mode < 0 || mode > 4)
889   {
890     *MSVCRT__errno() = MSVCRT_EINVAL;
891     return -1;
892   }
893
894   TRACE(":fd (%d) by 0x%08x mode %s\n",
895         fd,nbytes,(mode==MSVCRT__LK_UNLCK)?"_LK_UNLCK":
896         (mode==MSVCRT__LK_LOCK)?"_LK_LOCK":
897         (mode==MSVCRT__LK_NBLCK)?"_LK_NBLCK":
898         (mode==MSVCRT__LK_RLCK)?"_LK_RLCK":
899         (mode==MSVCRT__LK_NBRLCK)?"_LK_NBRLCK":
900                           "UNKNOWN");
901
902   if ((cur_locn = SetFilePointer(hand, 0L, NULL, SEEK_CUR)) == INVALID_SET_FILE_POINTER)
903   {
904     FIXME ("Seek failed\n");
905     *MSVCRT__errno() = MSVCRT_EINVAL; /* FIXME */
906     return -1;
907   }
908   if (mode == MSVCRT__LK_LOCK || mode == MSVCRT__LK_RLCK)
909   {
910     int nretry = 10;
911     ret = 1; /* just to satisfy gcc */
912     while (nretry--)
913     {
914       ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
915       if (ret) break;
916       Sleep(1);
917     }
918   }
919   else if (mode == MSVCRT__LK_UNLCK)
920     ret = UnlockFile(hand, cur_locn, 0L, nbytes, 0L);
921   else
922     ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
923   /* FIXME - what about error settings? */
924   return ret ? 0 : -1;
925 }
926
927 /*********************************************************************
928  *              fseek (MSVCRT.@)
929  */
930 int CDECL MSVCRT_fseek(MSVCRT_FILE* file, MSVCRT_long offset, int whence)
931 {
932   /* Flush output if needed */
933   if(file->_flag & MSVCRT__IOWRT)
934         msvcrt_flush_buffer(file);
935
936   if(whence == SEEK_CUR && file->_flag & MSVCRT__IOREAD ) {
937         offset -= file->_cnt;
938         if (MSVCRT_fdesc[file->_file].wxflag & WX_TEXT) {
939                 /* Black magic correction for CR removal */
940                 int i;
941                 for (i=0; i<file->_cnt; i++) {
942                         if (file->_ptr[i] == '\n')
943                                 offset--;
944                 }
945                 /* Black magic when reading CR at buffer boundary*/
946                 if(MSVCRT_fdesc[file->_file].wxflag & WX_READCR)
947                     offset--;
948         }
949   }
950   /* Discard buffered input */
951   file->_cnt = 0;
952   file->_ptr = file->_base;
953   /* Reset direction of i/o */
954   if(file->_flag & MSVCRT__IORW) {
955         file->_flag &= ~(MSVCRT__IOREAD|MSVCRT__IOWRT);
956   }
957   /* Clear end of file flag */
958   file->_flag &= ~MSVCRT__IOEOF;
959   return (MSVCRT__lseek(file->_file,offset,whence) == -1)?-1:0;
960 }
961
962 /*********************************************************************
963  *              _chsize (MSVCRT.@)
964  */
965 int CDECL _chsize(int fd, MSVCRT_long size)
966 {
967     LONG cur, pos;
968     HANDLE handle;
969     BOOL ret = FALSE;
970
971     TRACE("(fd=%d, size=%d)\n", fd, size);
972
973     LOCK_FILES();
974
975     handle = msvcrt_fdtoh(fd);
976     if (handle != INVALID_HANDLE_VALUE)
977     {
978         /* save the current file pointer */
979         cur = MSVCRT__lseek(fd, 0, SEEK_CUR);
980         if (cur >= 0)
981         {
982             pos = MSVCRT__lseek(fd, size, SEEK_SET);
983             if (pos >= 0)
984             {
985                 ret = SetEndOfFile(handle);
986                 if (!ret) msvcrt_set_errno(GetLastError());
987             }
988
989             /* restore the file pointer */
990             MSVCRT__lseek(fd, cur, SEEK_SET);
991         }
992     }
993
994     UNLOCK_FILES();
995     return ret ? 0 : -1;
996 }
997
998 /*********************************************************************
999  *              clearerr (MSVCRT.@)
1000  */
1001 void CDECL MSVCRT_clearerr(MSVCRT_FILE* file)
1002 {
1003   TRACE(":file (%p) fd (%d)\n",file,file->_file);
1004   file->_flag &= ~(MSVCRT__IOERR | MSVCRT__IOEOF);
1005 }
1006
1007 /*********************************************************************
1008  *              rewind (MSVCRT.@)
1009  */
1010 void CDECL MSVCRT_rewind(MSVCRT_FILE* file)
1011 {
1012   TRACE(":file (%p) fd (%d)\n",file,file->_file);
1013   MSVCRT_fseek(file, 0L, SEEK_SET);
1014   MSVCRT_clearerr(file);
1015 }
1016
1017 static int msvcrt_get_flags(const MSVCRT_wchar_t* mode, int *open_flags, int* stream_flags)
1018 {
1019   int plus = strchrW(mode, '+') != NULL;
1020
1021   switch(*mode++)
1022   {
1023   case 'R': case 'r':
1024     *open_flags = plus ? MSVCRT__O_RDWR : MSVCRT__O_RDONLY;
1025     *stream_flags = plus ? MSVCRT__IORW : MSVCRT__IOREAD;
1026     break;
1027   case 'W': case 'w':
1028     *open_flags = MSVCRT__O_CREAT | MSVCRT__O_TRUNC | (plus  ? MSVCRT__O_RDWR : MSVCRT__O_WRONLY);
1029     *stream_flags = plus ? MSVCRT__IORW : MSVCRT__IOWRT;
1030     break;
1031   case 'A': case 'a':
1032     *open_flags = MSVCRT__O_CREAT | MSVCRT__O_APPEND | (plus  ? MSVCRT__O_RDWR : MSVCRT__O_WRONLY);
1033     *stream_flags = plus ? MSVCRT__IORW : MSVCRT__IOWRT;
1034     break;
1035   default:
1036     return -1;
1037   }
1038
1039   while (*mode)
1040     switch (*mode++)
1041     {
1042     case 'B': case 'b':
1043       *open_flags |=  MSVCRT__O_BINARY;
1044       *open_flags &= ~MSVCRT__O_TEXT;
1045       break;
1046     case 'T': case 't':
1047       *open_flags |=  MSVCRT__O_TEXT;
1048       *open_flags &= ~MSVCRT__O_BINARY;
1049       break;
1050     case '+':
1051     case ' ':
1052       break;
1053     default:
1054       FIXME(":unknown flag %c not supported\n",mode[-1]);
1055     }
1056   return 0;
1057 }
1058
1059 /*********************************************************************
1060  *              _fdopen (MSVCRT.@)
1061  */
1062 MSVCRT_FILE* CDECL MSVCRT__fdopen(int fd, const char *mode)
1063 {
1064     MSVCRT_FILE *ret;
1065     MSVCRT_wchar_t *modeW = NULL;
1066
1067     if (mode && !(modeW = msvcrt_wstrdupa(mode))) return NULL;
1068
1069     ret = MSVCRT__wfdopen(fd, modeW);
1070
1071     MSVCRT_free(modeW);
1072     return ret;
1073 }
1074
1075 /*********************************************************************
1076  *              _wfdopen (MSVCRT.@)
1077  */
1078 MSVCRT_FILE* CDECL MSVCRT__wfdopen(int fd, const MSVCRT_wchar_t *mode)
1079 {
1080   int open_flags, stream_flags;
1081   MSVCRT_FILE* file;
1082
1083   if (msvcrt_get_flags(mode, &open_flags, &stream_flags) == -1) return NULL;
1084
1085   LOCK_FILES();
1086   if (!(file = msvcrt_alloc_fp()))
1087     file = NULL;
1088   else if (msvcrt_init_fp(file, fd, stream_flags) == -1)
1089   {
1090     file->_flag = 0;
1091     file = NULL;
1092   }
1093   else TRACE(":fd (%d) mode (%s) FILE* (%p)\n", fd, debugstr_w(mode), file);
1094   UNLOCK_FILES();
1095
1096   return file;
1097 }
1098
1099 /*********************************************************************
1100  *              _filelength (MSVCRT.@)
1101  */
1102 LONG CDECL MSVCRT__filelength(int fd)
1103 {
1104   LONG curPos = MSVCRT__lseek(fd, 0, SEEK_CUR);
1105   if (curPos != -1)
1106   {
1107     LONG endPos = MSVCRT__lseek(fd, 0, SEEK_END);
1108     if (endPos != -1)
1109     {
1110       if (endPos != curPos)
1111         MSVCRT__lseek(fd, curPos, SEEK_SET);
1112       return endPos;
1113     }
1114   }
1115   return -1;
1116 }
1117
1118 /*********************************************************************
1119  *              _filelengthi64 (MSVCRT.@)
1120  */
1121 __int64 CDECL MSVCRT__filelengthi64(int fd)
1122 {
1123   __int64 curPos = MSVCRT__lseeki64(fd, 0, SEEK_CUR);
1124   if (curPos != -1)
1125   {
1126     __int64 endPos = MSVCRT__lseeki64(fd, 0, SEEK_END);
1127     if (endPos != -1)
1128     {
1129       if (endPos != curPos)
1130         MSVCRT__lseeki64(fd, curPos, SEEK_SET);
1131       return endPos;
1132     }
1133   }
1134   return -1;
1135 }
1136
1137 /*********************************************************************
1138  *              _fileno (MSVCRT.@)
1139  */
1140 int CDECL MSVCRT__fileno(MSVCRT_FILE* file)
1141 {
1142   TRACE(":FILE* (%p) fd (%d)\n",file,file->_file);
1143   return file->_file;
1144 }
1145
1146 /*********************************************************************
1147  *              _fstat64 (MSVCRT.@)
1148  */
1149 int CDECL MSVCRT__fstat64(int fd, struct MSVCRT__stat64* buf)
1150 {
1151   DWORD dw;
1152   DWORD type;
1153   BY_HANDLE_FILE_INFORMATION hfi;
1154   HANDLE hand = msvcrt_fdtoh(fd);
1155
1156   TRACE(":fd (%d) stat (%p)\n",fd,buf);
1157   if (hand == INVALID_HANDLE_VALUE)
1158     return -1;
1159
1160   if (!buf)
1161   {
1162     WARN(":failed-NULL buf\n");
1163     msvcrt_set_errno(ERROR_INVALID_PARAMETER);
1164     return -1;
1165   }
1166
1167   memset(&hfi, 0, sizeof(hfi));
1168   memset(buf, 0, sizeof(struct MSVCRT__stat64));
1169   type = GetFileType(hand);
1170   if (type == FILE_TYPE_PIPE)
1171   {
1172     buf->st_dev = buf->st_rdev = fd;
1173     buf->st_mode = S_IFIFO;
1174     buf->st_nlink = 1;
1175   }
1176   else if (type == FILE_TYPE_CHAR)
1177   {
1178     buf->st_dev = buf->st_rdev = fd;
1179     buf->st_mode = S_IFCHR;
1180     buf->st_nlink = 1;
1181   }
1182   else /* FILE_TYPE_DISK etc. */
1183   {
1184     if (!GetFileInformationByHandle(hand, &hfi))
1185     {
1186       WARN(":failed-last error (%d)\n",GetLastError());
1187       msvcrt_set_errno(ERROR_INVALID_PARAMETER);
1188       return -1;
1189     }
1190     buf->st_mode = S_IFREG | 0444;
1191     if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1192       buf->st_mode |= 0222;
1193     buf->st_size  = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
1194     RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
1195     buf->st_atime = dw;
1196     RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
1197     buf->st_mtime = buf->st_ctime = dw;
1198     buf->st_nlink = hfi.nNumberOfLinks;
1199   }
1200   TRACE(":dwFileAttributes = 0x%x, mode set to 0x%x\n",hfi.dwFileAttributes,
1201    buf->st_mode);
1202   return 0;
1203 }
1204
1205 /*********************************************************************
1206  *              _fstati64 (MSVCRT.@)
1207  */
1208 int CDECL MSVCRT__fstati64(int fd, struct MSVCRT__stati64* buf)
1209 {
1210   int ret;
1211   struct MSVCRT__stat64 buf64;
1212
1213   ret = MSVCRT__fstat64(fd, &buf64);
1214   if (!ret)
1215     msvcrt_stat64_to_stati64(&buf64, buf);
1216   return ret;
1217 }
1218
1219 /*********************************************************************
1220  *              _fstat (MSVCRT.@)
1221  */
1222 int CDECL MSVCRT__fstat(int fd, struct MSVCRT__stat* buf)
1223 { int ret;
1224   struct MSVCRT__stat64 buf64;
1225
1226   ret = MSVCRT__fstat64(fd, &buf64);
1227   if (!ret)
1228       msvcrt_stat64_to_stat(&buf64, buf);
1229   return ret;
1230 }
1231
1232 /*********************************************************************
1233  *              _futime64 (MSVCRT.@)
1234  */
1235 int CDECL _futime64(int fd, struct MSVCRT___utimbuf64 *t)
1236 {
1237   HANDLE hand = msvcrt_fdtoh(fd);
1238   FILETIME at, wt;
1239
1240   if (!t)
1241   {
1242       time_to_filetime( MSVCRT__time64(NULL), &at );
1243       wt = at;
1244   }
1245   else
1246   {
1247       time_to_filetime( t->actime, &at );
1248       time_to_filetime( t->modtime, &wt );
1249   }
1250
1251   if (!SetFileTime(hand, NULL, &at, &wt))
1252   {
1253     msvcrt_set_errno(GetLastError());
1254     return -1 ;
1255   }
1256   return 0;
1257 }
1258
1259 /*********************************************************************
1260  *              _futime32 (MSVCRT.@)
1261  */
1262 int CDECL _futime32(int fd, struct MSVCRT___utimbuf32 *t)
1263 {
1264     struct MSVCRT___utimbuf64 t64;
1265     t64.actime = t->actime;
1266     t64.modtime = t->modtime;
1267     return _futime64( fd, &t64 );
1268 }
1269
1270 /*********************************************************************
1271  *              _futime (MSVCRT.@)
1272  */
1273 #ifdef _WIN64
1274 int CDECL _futime(int fd, struct MSVCRT___utimbuf64 *t)
1275 {
1276     return _futime64( fd, t );
1277 }
1278 #else
1279 int CDECL _futime(int fd, struct MSVCRT___utimbuf32 *t)
1280 {
1281     return _futime32( fd, t );
1282 }
1283 #endif
1284
1285 /*********************************************************************
1286  *              _get_osfhandle (MSVCRT.@)
1287  */
1288 MSVCRT_intptr_t CDECL _get_osfhandle(int fd)
1289 {
1290   HANDLE hand = msvcrt_fdtoh(fd);
1291   TRACE(":fd (%d) handle (%p)\n",fd,hand);
1292
1293   return (MSVCRT_intptr_t)hand;
1294 }
1295
1296 /*********************************************************************
1297  *              _isatty (MSVCRT.@)
1298  */
1299 int CDECL _isatty(int fd)
1300 {
1301   HANDLE hand = msvcrt_fdtoh(fd);
1302
1303   TRACE(":fd (%d) handle (%p)\n",fd,hand);
1304   if (hand == INVALID_HANDLE_VALUE)
1305     return 0;
1306
1307   return GetFileType(hand) == FILE_TYPE_CHAR? 1 : 0;
1308 }
1309
1310 /*********************************************************************
1311  *              _mktemp (MSVCRT.@)
1312  */
1313 char * CDECL _mktemp(char *pattern)
1314 {
1315   int numX = 0;
1316   char *retVal = pattern;
1317   int id;
1318   char letter = 'a';
1319
1320   while(*pattern)
1321     numX = (*pattern++ == 'X')? numX + 1 : 0;
1322   if (numX < 5)
1323     return NULL;
1324   pattern--;
1325   id = GetCurrentProcessId();
1326   numX = 6;
1327   while(numX--)
1328   {
1329     int tempNum = id / 10;
1330     *pattern-- = id - (tempNum * 10) + '0';
1331     id = tempNum;
1332   }
1333   pattern++;
1334   do
1335   {
1336     *pattern = letter++;
1337     if (GetFileAttributesA(retVal) == INVALID_FILE_ATTRIBUTES &&
1338         GetLastError() == ERROR_FILE_NOT_FOUND)
1339       return retVal;
1340   } while(letter <= 'z');
1341   return NULL;
1342 }
1343
1344 /*********************************************************************
1345  *              _wmktemp (MSVCRT.@)
1346  */
1347 MSVCRT_wchar_t * CDECL _wmktemp(MSVCRT_wchar_t *pattern)
1348 {
1349   int numX = 0;
1350   MSVCRT_wchar_t *retVal = pattern;
1351   int id;
1352   MSVCRT_wchar_t letter = 'a';
1353
1354   while(*pattern)
1355     numX = (*pattern++ == 'X')? numX + 1 : 0;
1356   if (numX < 5)
1357     return NULL;
1358   pattern--;
1359   id = GetCurrentProcessId();
1360   numX = 6;
1361   while(numX--)
1362   {
1363     int tempNum = id / 10;
1364     *pattern-- = id - (tempNum * 10) + '0';
1365     id = tempNum;
1366   }
1367   pattern++;
1368   do
1369   {
1370     if (GetFileAttributesW(retVal) == INVALID_FILE_ATTRIBUTES &&
1371         GetLastError() == ERROR_FILE_NOT_FOUND)
1372       return retVal;
1373     *pattern = letter++;
1374   } while(letter != '|');
1375   return NULL;
1376 }
1377
1378 static unsigned split_oflags(unsigned oflags)
1379 {
1380     int         wxflags = 0;
1381     unsigned unsupp; /* until we support everything */
1382
1383     if (oflags & MSVCRT__O_APPEND)              wxflags |= WX_APPEND;
1384     if (oflags & MSVCRT__O_BINARY)              {/* Nothing to do */}
1385     else if (oflags & MSVCRT__O_TEXT)           wxflags |= WX_TEXT;
1386     else if (*__p__fmode() & MSVCRT__O_BINARY)  {/* Nothing to do */}
1387     else                                        wxflags |= WX_TEXT; /* default to TEXT*/
1388     if (oflags & MSVCRT__O_NOINHERIT)           wxflags |= WX_DONTINHERIT;
1389
1390     if ((unsupp = oflags & ~(
1391                     MSVCRT__O_BINARY|MSVCRT__O_TEXT|MSVCRT__O_APPEND|
1392                     MSVCRT__O_TRUNC|MSVCRT__O_EXCL|MSVCRT__O_CREAT|
1393                     MSVCRT__O_RDWR|MSVCRT__O_WRONLY|MSVCRT__O_TEMPORARY|
1394                     MSVCRT__O_NOINHERIT|
1395                     MSVCRT__O_SEQUENTIAL|MSVCRT__O_RANDOM|MSVCRT__O_SHORT_LIVED
1396                     )))
1397         ERR(":unsupported oflags 0x%04x\n",unsupp);
1398
1399     return wxflags;
1400 }
1401
1402 /*********************************************************************
1403  *              _pipe (MSVCRT.@)
1404  */
1405 int CDECL MSVCRT__pipe(int *pfds, unsigned int psize, int textmode)
1406 {
1407   int ret = -1;
1408   SECURITY_ATTRIBUTES sa;
1409   HANDLE readHandle, writeHandle;
1410
1411   if (!pfds)
1412   {
1413     *MSVCRT__errno() = MSVCRT_EINVAL;
1414     return -1;
1415   }
1416
1417   sa.nLength = sizeof(SECURITY_ATTRIBUTES);
1418   sa.bInheritHandle = !(textmode & MSVCRT__O_NOINHERIT);
1419   sa.lpSecurityDescriptor = NULL;
1420   if (CreatePipe(&readHandle, &writeHandle, &sa, psize))
1421   {
1422     unsigned int wxflags = split_oflags(textmode);
1423     int fd;
1424
1425     LOCK_FILES();
1426     fd = msvcrt_alloc_fd(readHandle, wxflags);
1427     if (fd != -1)
1428     {
1429       pfds[0] = fd;
1430       fd = msvcrt_alloc_fd(writeHandle, wxflags);
1431       if (fd != -1)
1432       {
1433         pfds[1] = fd;
1434         ret = 0;
1435       }
1436       else
1437       {
1438         MSVCRT__close(pfds[0]);
1439         CloseHandle(writeHandle);
1440         *MSVCRT__errno() = MSVCRT_EMFILE;
1441       }
1442     }
1443     else
1444     {
1445       CloseHandle(readHandle);
1446       CloseHandle(writeHandle);
1447       *MSVCRT__errno() = MSVCRT_EMFILE;
1448     }
1449     UNLOCK_FILES();
1450   }
1451   else
1452     msvcrt_set_errno(GetLastError());
1453
1454   return ret;
1455 }
1456
1457 /*********************************************************************
1458  *              _sopen (MSVCRT.@)
1459  */
1460 int CDECL MSVCRT__sopen( const char *path, int oflags, int shflags, ... )
1461 {
1462   __ms_va_list ap;
1463   int pmode;
1464   DWORD access = 0, creation = 0, attrib;
1465   DWORD sharing;
1466   int wxflag = 0, fd;
1467   HANDLE hand;
1468   SECURITY_ATTRIBUTES sa;
1469
1470
1471   TRACE(":file (%s) oflags: 0x%04x shflags: 0x%04x\n",
1472         path, oflags, shflags);
1473
1474   wxflag = split_oflags(oflags);
1475   switch (oflags & (MSVCRT__O_RDONLY | MSVCRT__O_WRONLY | MSVCRT__O_RDWR))
1476   {
1477   case MSVCRT__O_RDONLY: access |= GENERIC_READ; break;
1478   case MSVCRT__O_WRONLY: access |= GENERIC_WRITE; break;
1479   case MSVCRT__O_RDWR:   access |= GENERIC_WRITE | GENERIC_READ; break;
1480   }
1481
1482   if (oflags & MSVCRT__O_CREAT)
1483   {
1484     __ms_va_start(ap, shflags);
1485     pmode = va_arg(ap, int);
1486     __ms_va_end(ap);
1487
1488     if(pmode & ~(MSVCRT__S_IREAD | MSVCRT__S_IWRITE))
1489       FIXME(": pmode 0x%04x ignored\n", pmode);
1490     else
1491       WARN(": pmode 0x%04x ignored\n", pmode);
1492
1493     if (oflags & MSVCRT__O_EXCL)
1494       creation = CREATE_NEW;
1495     else if (oflags & MSVCRT__O_TRUNC)
1496       creation = CREATE_ALWAYS;
1497     else
1498       creation = OPEN_ALWAYS;
1499   }
1500   else  /* no MSVCRT__O_CREAT */
1501   {
1502     if (oflags & MSVCRT__O_TRUNC)
1503       creation = TRUNCATE_EXISTING;
1504     else
1505       creation = OPEN_EXISTING;
1506   }
1507   
1508   switch( shflags )
1509   {
1510     case MSVCRT__SH_DENYRW:
1511       sharing = 0L;
1512       break;
1513     case MSVCRT__SH_DENYWR:
1514       sharing = FILE_SHARE_READ;
1515       break;
1516     case MSVCRT__SH_DENYRD:
1517       sharing = FILE_SHARE_WRITE;
1518       break;
1519     case MSVCRT__SH_DENYNO:
1520       sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
1521       break;
1522     default:
1523       ERR( "Unhandled shflags 0x%x\n", shflags );
1524       return -1;
1525   }
1526   attrib = FILE_ATTRIBUTE_NORMAL;
1527
1528   if (oflags & MSVCRT__O_TEMPORARY)
1529   {
1530       attrib |= FILE_FLAG_DELETE_ON_CLOSE;
1531       access |= DELETE;
1532       sharing |= FILE_SHARE_DELETE;
1533   }
1534
1535   sa.nLength              = sizeof( SECURITY_ATTRIBUTES );
1536   sa.lpSecurityDescriptor = NULL;
1537   sa.bInheritHandle       = (oflags & MSVCRT__O_NOINHERIT) ? FALSE : TRUE;
1538
1539   hand = CreateFileA(path, access, sharing, &sa, creation, attrib, 0);
1540
1541   if (hand == INVALID_HANDLE_VALUE)  {
1542     WARN(":failed-last error (%d)\n",GetLastError());
1543     msvcrt_set_errno(GetLastError());
1544     return -1;
1545   }
1546
1547   fd = msvcrt_alloc_fd(hand, wxflag);
1548
1549   TRACE(":fd (%d) handle (%p)\n",fd, hand);
1550   return fd;
1551 }
1552
1553 /*********************************************************************
1554  *              _wsopen (MSVCRT.@)
1555  */
1556 int CDECL MSVCRT__wsopen( const MSVCRT_wchar_t* path, int oflags, int shflags, ... )
1557 {
1558   __ms_va_list ap;
1559   int pmode;
1560   DWORD access = 0, creation = 0, attrib;
1561   DWORD sharing;
1562   int wxflag = 0, fd;
1563   HANDLE hand;
1564   SECURITY_ATTRIBUTES sa;
1565
1566
1567   TRACE(":file (%s) oflags: 0x%04x shflags: 0x%04x\n",
1568         debugstr_w(path), oflags, shflags);
1569
1570   wxflag = split_oflags(oflags);
1571   switch (oflags & (MSVCRT__O_RDONLY | MSVCRT__O_WRONLY | MSVCRT__O_RDWR))
1572   {
1573   case MSVCRT__O_RDONLY: access |= GENERIC_READ; break;
1574   case MSVCRT__O_WRONLY: access |= GENERIC_WRITE; break;
1575   case MSVCRT__O_RDWR:   access |= GENERIC_WRITE | GENERIC_READ; break;
1576   }
1577
1578   if (oflags & MSVCRT__O_CREAT)
1579   {
1580     __ms_va_start(ap, shflags);
1581     pmode = va_arg(ap, int);
1582     __ms_va_end(ap);
1583
1584     if(pmode & ~(MSVCRT__S_IREAD | MSVCRT__S_IWRITE))
1585       FIXME(": pmode 0x%04x ignored\n", pmode);
1586     else
1587       WARN(": pmode 0x%04x ignored\n", pmode);
1588
1589     if (oflags & MSVCRT__O_EXCL)
1590       creation = CREATE_NEW;
1591     else if (oflags & MSVCRT__O_TRUNC)
1592       creation = CREATE_ALWAYS;
1593     else
1594       creation = OPEN_ALWAYS;
1595   }
1596   else  /* no MSVCRT__O_CREAT */
1597   {
1598     if (oflags & MSVCRT__O_TRUNC)
1599       creation = TRUNCATE_EXISTING;
1600     else
1601       creation = OPEN_EXISTING;
1602   }
1603
1604   switch( shflags )
1605   {
1606     case MSVCRT__SH_DENYRW:
1607       sharing = 0L;
1608       break;
1609     case MSVCRT__SH_DENYWR:
1610       sharing = FILE_SHARE_READ;
1611       break;
1612     case MSVCRT__SH_DENYRD:
1613       sharing = FILE_SHARE_WRITE;
1614       break;
1615     case MSVCRT__SH_DENYNO:
1616       sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
1617       break;
1618     default:
1619       ERR( "Unhandled shflags 0x%x\n", shflags );
1620       return -1;
1621   }
1622   attrib = FILE_ATTRIBUTE_NORMAL;
1623
1624   if (oflags & MSVCRT__O_TEMPORARY)
1625   {
1626       attrib |= FILE_FLAG_DELETE_ON_CLOSE;
1627       access |= DELETE;
1628       sharing |= FILE_SHARE_DELETE;
1629   }
1630
1631   sa.nLength              = sizeof( SECURITY_ATTRIBUTES );
1632   sa.lpSecurityDescriptor = NULL;
1633   sa.bInheritHandle       = (oflags & MSVCRT__O_NOINHERIT) ? FALSE : TRUE;
1634
1635   hand = CreateFileW(path, access, sharing, &sa, creation, attrib, 0);
1636
1637   if (hand == INVALID_HANDLE_VALUE)  {
1638     WARN(":failed-last error (%d)\n",GetLastError());
1639     msvcrt_set_errno(GetLastError());
1640     return -1;
1641   }
1642
1643   fd = msvcrt_alloc_fd(hand, wxflag);
1644
1645   TRACE(":fd (%d) handle (%p)\n",fd, hand);
1646   return fd;
1647 }
1648
1649 /*********************************************************************
1650  *              _open (MSVCRT.@)
1651  */
1652 int CDECL MSVCRT__open( const char *path, int flags, ... )
1653 {
1654   __ms_va_list ap;
1655
1656   if (flags & MSVCRT__O_CREAT)
1657   {
1658     int pmode;
1659     __ms_va_start(ap, flags);
1660     pmode = va_arg(ap, int);
1661     __ms_va_end(ap);
1662     return MSVCRT__sopen( path, flags, MSVCRT__SH_DENYNO, pmode );
1663   }
1664   else
1665     return MSVCRT__sopen( path, flags, MSVCRT__SH_DENYNO);
1666 }
1667
1668 /*********************************************************************
1669  *              _wopen (MSVCRT.@)
1670  */
1671 int CDECL _wopen(const MSVCRT_wchar_t *path,int flags,...)
1672 {
1673   __ms_va_list ap;
1674
1675   if (flags & MSVCRT__O_CREAT)
1676   {
1677     int pmode;
1678     __ms_va_start(ap, flags);
1679     pmode = va_arg(ap, int);
1680     __ms_va_end(ap);
1681     return MSVCRT__wsopen( path, flags, MSVCRT__SH_DENYNO, pmode );
1682   }
1683   else
1684     return MSVCRT__wsopen( path, flags, MSVCRT__SH_DENYNO);
1685 }
1686
1687 /*********************************************************************
1688  *              _creat (MSVCRT.@)
1689  */
1690 int CDECL MSVCRT__creat(const char *path, int flags)
1691 {
1692   int usedFlags = (flags & MSVCRT__O_TEXT)| MSVCRT__O_CREAT| MSVCRT__O_WRONLY| MSVCRT__O_TRUNC;
1693   return MSVCRT__open(path, usedFlags);
1694 }
1695
1696 /*********************************************************************
1697  *              _wcreat (MSVCRT.@)
1698  */
1699 int CDECL _wcreat(const MSVCRT_wchar_t *path, int flags)
1700 {
1701   int usedFlags = (flags & MSVCRT__O_TEXT)| MSVCRT__O_CREAT| MSVCRT__O_WRONLY| MSVCRT__O_TRUNC;
1702   return _wopen(path, usedFlags);
1703 }
1704
1705 /*********************************************************************
1706  *              _open_osfhandle (MSVCRT.@)
1707  */
1708 int CDECL _open_osfhandle(MSVCRT_intptr_t handle, int oflags)
1709 {
1710   int fd;
1711
1712   /* MSVCRT__O_RDONLY (0) always matches, so set the read flag
1713    * MFC's CStdioFile clears O_RDONLY (0)! if it wants to write to the
1714    * file, so set the write flag. It also only sets MSVCRT__O_TEXT if it wants
1715    * text - it never sets MSVCRT__O_BINARY.
1716    */
1717   /* don't let split_oflags() decide the mode if no mode is passed */
1718   if (!(oflags & (MSVCRT__O_BINARY | MSVCRT__O_TEXT)))
1719       oflags |= MSVCRT__O_BINARY;
1720
1721   fd = msvcrt_alloc_fd((HANDLE)handle, split_oflags(oflags));
1722   TRACE(":handle (%ld) fd (%d) flags 0x%08x\n", handle, fd, oflags);
1723   return fd;
1724 }
1725
1726 /*********************************************************************
1727  *              _rmtmp (MSVCRT.@)
1728  */
1729 int CDECL _rmtmp(void)
1730 {
1731   int num_removed = 0, i;
1732
1733   LOCK_FILES();
1734   for (i = 3; i < MSVCRT_stream_idx; i++)
1735     if (MSVCRT_fstreams[i] && MSVCRT_fstreams[i]->_tmpfname)
1736     {
1737       MSVCRT_fclose(MSVCRT_fstreams[i]);
1738       num_removed++;
1739     }
1740   UNLOCK_FILES();
1741
1742   if (num_removed)
1743     TRACE(":removed (%d) temp files\n",num_removed);
1744   return num_removed;
1745 }
1746
1747 /*********************************************************************
1748  * (internal) read_i
1749  *
1750  * When reading \r as last character in text mode, read() positions
1751  * the file pointer on the \r character while getc() goes on to
1752  * the following \n
1753  */
1754 static int read_i(int fd, void *buf, unsigned int count)
1755 {
1756   DWORD num_read;
1757   char *bufstart = buf;
1758   HANDLE hand = msvcrt_fdtoh(fd);
1759
1760   if (MSVCRT_fdesc[fd].wxflag & WX_READEOF) {
1761      MSVCRT_fdesc[fd].wxflag |= WX_ATEOF;
1762      TRACE("already at EOF, returning 0\n");
1763      return 0;
1764   }
1765   /* Don't trace small reads, it gets *very* annoying */
1766   if (count > 4)
1767     TRACE(":fd (%d) handle (%p) buf (%p) len (%d)\n",fd,hand,buf,count);
1768   if (hand == INVALID_HANDLE_VALUE)
1769     return -1;
1770
1771   /* Reading single bytes in O_TEXT mode makes things slow
1772    * So read big chunks
1773    */
1774     if (ReadFile(hand, bufstart, count, &num_read, NULL))
1775     {
1776         if (MSVCRT_fdesc[fd].wxflag & WX_TEXT)
1777         {
1778             DWORD i, j;
1779             if (bufstart[num_read-1] == '\r')
1780             {
1781                 MSVCRT_fdesc[fd].wxflag  |= WX_READCR;
1782                 num_read--;
1783             }
1784             else
1785               MSVCRT_fdesc[fd].wxflag  &=  ~WX_READCR;
1786             for (i=0, j=0; i<num_read; i++)
1787             {
1788                 /* in text mode, a ctrl-z signals EOF */
1789                 if (bufstart[i] == 0x1a)
1790                 {
1791                     MSVCRT_fdesc[fd].wxflag |= (WX_ATEOF|WX_READEOF);
1792                     TRACE(":^Z EOF %s\n",debugstr_an(buf,num_read));
1793                     break;
1794                 }
1795                 /* in text mode, strip \r if followed by \n.
1796                  * BUG: should save state across calls somehow, so CR LF that
1797                  * straddles buffer boundary gets recognized properly?
1798                  */
1799                 if ((bufstart[i] != '\r')
1800                 ||  ((i+1) < num_read && bufstart[i+1] != '\n'))
1801                     bufstart[j++] = bufstart[i];
1802             }
1803             num_read = j;
1804         }
1805         if (count != 0 && num_read == 0)
1806         {
1807             MSVCRT_fdesc[fd].wxflag |= (WX_ATEOF|WX_READEOF);
1808             TRACE(":EOF %s\n",debugstr_an(buf,num_read));
1809         }
1810     }
1811     else
1812     {
1813         if (GetLastError() == ERROR_BROKEN_PIPE)
1814         {
1815             TRACE(":end-of-pipe\n");
1816             MSVCRT_fdesc[fd].wxflag |= (WX_ATEOF|WX_READEOF);
1817             return 0;
1818         }
1819         else
1820         {
1821             TRACE(":failed-last error (%d)\n",GetLastError());
1822             return -1;
1823         }
1824     }
1825
1826   if (count > 4)
1827       TRACE("(%u), %s\n",num_read,debugstr_an(buf, num_read));
1828   return num_read;
1829 }
1830
1831 /*********************************************************************
1832  *              _read (MSVCRT.@)
1833  */
1834 int CDECL MSVCRT__read(int fd, void *buf, unsigned int count)
1835 {
1836   int num_read;
1837   num_read = read_i(fd, buf, count);
1838   return num_read;
1839 }
1840
1841 /*********************************************************************
1842  *              _setmode (MSVCRT.@)
1843  */
1844 int CDECL _setmode(int fd,int mode)
1845 {
1846   int ret = MSVCRT_fdesc[fd].wxflag & WX_TEXT ? MSVCRT__O_TEXT : MSVCRT__O_BINARY;
1847   if (mode & (~(MSVCRT__O_TEXT|MSVCRT__O_BINARY)))
1848     FIXME("fd (%d) mode (0x%08x) unknown\n",fd,mode);
1849   if ((mode & MSVCRT__O_TEXT) == MSVCRT__O_TEXT)
1850     MSVCRT_fdesc[fd].wxflag |= WX_TEXT;
1851   else
1852     MSVCRT_fdesc[fd].wxflag &= ~WX_TEXT;
1853   return ret;
1854 }
1855
1856 /*********************************************************************
1857  *              _stat64 (MSVCRT.@)
1858  */
1859 int CDECL MSVCRT_stat64(const char* path, struct MSVCRT__stat64 * buf)
1860 {
1861   DWORD dw;
1862   WIN32_FILE_ATTRIBUTE_DATA hfi;
1863   unsigned short mode = ALL_S_IREAD;
1864   int plen;
1865
1866   TRACE(":file (%s) buf(%p)\n",path,buf);
1867
1868   if (!GetFileAttributesExA(path, GetFileExInfoStandard, &hfi))
1869   {
1870       TRACE("failed (%d)\n",GetLastError());
1871       msvcrt_set_errno(ERROR_FILE_NOT_FOUND);
1872       return -1;
1873   }
1874
1875   memset(buf,0,sizeof(struct MSVCRT__stat64));
1876
1877   /* FIXME: rdev isn't drive num, despite what the docs say-what is it?
1878      Bon 011120: This FIXME seems incorrect
1879                  Also a letter as first char isn't enough to be classified
1880                  as a drive letter
1881   */
1882   if (isalpha(*path)&& (*(path+1)==':'))
1883     buf->st_dev = buf->st_rdev = toupper(*path) - 'A'; /* drive num */
1884   else
1885     buf->st_dev = buf->st_rdev = _getdrive() - 1;
1886
1887   plen = strlen(path);
1888
1889   /* Dir, or regular file? */
1890   if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1891       (path[plen-1] == '\\'))
1892     mode |= (MSVCRT__S_IFDIR | ALL_S_IEXEC);
1893   else
1894   {
1895     mode |= MSVCRT__S_IFREG;
1896     /* executable? */
1897     if (plen > 6 && path[plen-4] == '.')  /* shortest exe: "\x.exe" */
1898     {
1899       unsigned int ext = tolower(path[plen-1]) | (tolower(path[plen-2]) << 8) |
1900                                  (tolower(path[plen-3]) << 16);
1901       if (ext == EXE || ext == BAT || ext == CMD || ext == COM)
1902           mode |= ALL_S_IEXEC;
1903     }
1904   }
1905
1906   if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1907     mode |= ALL_S_IWRITE;
1908
1909   buf->st_mode  = mode;
1910   buf->st_nlink = 1;
1911   buf->st_size  = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
1912   RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
1913   buf->st_atime = dw;
1914   RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
1915   buf->st_mtime = buf->st_ctime = dw;
1916   TRACE("%d %d 0x%08x%08x %d %d %d\n", buf->st_mode,buf->st_nlink,
1917         (int)(buf->st_size >> 32),(int)buf->st_size,
1918         (int)buf->st_atime,(int)buf->st_mtime,(int)buf->st_ctime);
1919   return 0;
1920 }
1921
1922 /*********************************************************************
1923  *              _stati64 (MSVCRT.@)
1924  */
1925 int CDECL MSVCRT_stati64(const char* path, struct MSVCRT__stati64 * buf)
1926 {
1927   int ret;
1928   struct MSVCRT__stat64 buf64;
1929
1930   ret = MSVCRT_stat64(path, &buf64);
1931   if (!ret)
1932     msvcrt_stat64_to_stati64(&buf64, buf);
1933   return ret;
1934 }
1935
1936 /*********************************************************************
1937  *              _stat (MSVCRT.@)
1938  */
1939 int CDECL MSVCRT_stat(const char* path, struct MSVCRT__stat * buf)
1940 { int ret;
1941   struct MSVCRT__stat64 buf64;
1942
1943   ret = MSVCRT_stat64( path, &buf64);
1944   if (!ret)
1945       msvcrt_stat64_to_stat(&buf64, buf);
1946   return ret;
1947 }
1948
1949 /*********************************************************************
1950  *              _wstat64 (MSVCRT.@)
1951  */
1952 int CDECL MSVCRT__wstat64(const MSVCRT_wchar_t* path, struct MSVCRT__stat64 * buf)
1953 {
1954   DWORD dw;
1955   WIN32_FILE_ATTRIBUTE_DATA hfi;
1956   unsigned short mode = ALL_S_IREAD;
1957   int plen;
1958
1959   TRACE(":file (%s) buf(%p)\n",debugstr_w(path),buf);
1960
1961   if (!GetFileAttributesExW(path, GetFileExInfoStandard, &hfi))
1962   {
1963       TRACE("failed (%d)\n",GetLastError());
1964       msvcrt_set_errno(ERROR_FILE_NOT_FOUND);
1965       return -1;
1966   }
1967
1968   memset(buf,0,sizeof(struct MSVCRT__stat64));
1969
1970   /* FIXME: rdev isn't drive num, despite what the docs says-what is it? */
1971   if (MSVCRT_iswalpha(*path))
1972     buf->st_dev = buf->st_rdev = toupperW(*path - 'A'); /* drive num */
1973   else
1974     buf->st_dev = buf->st_rdev = _getdrive() - 1;
1975
1976   plen = strlenW(path);
1977
1978   /* Dir, or regular file? */
1979   if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1980       (path[plen-1] == '\\'))
1981     mode |= (MSVCRT__S_IFDIR | ALL_S_IEXEC);
1982   else
1983   {
1984     mode |= MSVCRT__S_IFREG;
1985     /* executable? */
1986     if (plen > 6 && path[plen-4] == '.')  /* shortest exe: "\x.exe" */
1987     {
1988       ULONGLONG ext = tolowerW(path[plen-1]) | (tolowerW(path[plen-2]) << 16) |
1989                                ((ULONGLONG)tolowerW(path[plen-3]) << 32);
1990       if (ext == WCEXE || ext == WCBAT || ext == WCCMD || ext == WCCOM)
1991         mode |= ALL_S_IEXEC;
1992     }
1993   }
1994
1995   if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1996     mode |= ALL_S_IWRITE;
1997
1998   buf->st_mode  = mode;
1999   buf->st_nlink = 1;
2000   buf->st_size  = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
2001   RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
2002   buf->st_atime = dw;
2003   RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
2004   buf->st_mtime = buf->st_ctime = dw;
2005   TRACE("%d %d 0x%08x%08x %d %d %d\n", buf->st_mode,buf->st_nlink,
2006         (int)(buf->st_size >> 32),(int)buf->st_size,
2007         (int)buf->st_atime,(int)buf->st_mtime,(int)buf->st_ctime);
2008   return 0;
2009 }
2010
2011 /*********************************************************************
2012  *              _wstati64 (MSVCRT.@)
2013  */
2014 int CDECL MSVCRT__wstati64(const MSVCRT_wchar_t* path, struct MSVCRT__stati64 * buf)
2015 {
2016   int ret;
2017   struct MSVCRT__stat64 buf64;
2018
2019   ret = MSVCRT__wstat64(path, &buf64);
2020   if (!ret)
2021     msvcrt_stat64_to_stati64(&buf64, buf);
2022   return ret;
2023 }
2024
2025 /*********************************************************************
2026  *              _wstat (MSVCRT.@)
2027  */
2028 int CDECL MSVCRT__wstat(const MSVCRT_wchar_t* path, struct MSVCRT__stat * buf)
2029 {
2030   int ret;
2031   struct MSVCRT__stat64 buf64;
2032
2033   ret = MSVCRT__wstat64( path, &buf64 );
2034   if (!ret) msvcrt_stat64_to_stat(&buf64, buf);
2035   return ret;
2036 }
2037
2038 /*********************************************************************
2039  *              _tell (MSVCRT.@)
2040  */
2041 MSVCRT_long CDECL _tell(int fd)
2042 {
2043   return MSVCRT__lseek(fd, 0, SEEK_CUR);
2044 }
2045
2046 /*********************************************************************
2047  *              _telli64 (MSVCRT.@)
2048  */
2049 __int64 CDECL _telli64(int fd)
2050 {
2051   return MSVCRT__lseeki64(fd, 0, SEEK_CUR);
2052 }
2053
2054 /*********************************************************************
2055  *              _tempnam (MSVCRT.@)
2056  */
2057 char * CDECL _tempnam(const char *dir, const char *prefix)
2058 {
2059   char tmpbuf[MAX_PATH];
2060   const char *tmp_dir = MSVCRT_getenv("TMP");
2061
2062   if (tmp_dir) dir = tmp_dir;
2063
2064   TRACE("dir (%s) prefix (%s)\n",dir,prefix);
2065   if (GetTempFileNameA(dir,prefix,0,tmpbuf))
2066   {
2067     TRACE("got name (%s)\n",tmpbuf);
2068     DeleteFileA(tmpbuf);
2069     return _strdup(tmpbuf);
2070   }
2071   TRACE("failed (%d)\n",GetLastError());
2072   return NULL;
2073 }
2074
2075 /*********************************************************************
2076  *              _wtempnam (MSVCRT.@)
2077  */
2078 MSVCRT_wchar_t * CDECL _wtempnam(const MSVCRT_wchar_t *dir, const MSVCRT_wchar_t *prefix)
2079 {
2080   MSVCRT_wchar_t tmpbuf[MAX_PATH];
2081
2082   TRACE("dir (%s) prefix (%s)\n",debugstr_w(dir),debugstr_w(prefix));
2083   if (GetTempFileNameW(dir,prefix,0,tmpbuf))
2084   {
2085     TRACE("got name (%s)\n",debugstr_w(tmpbuf));
2086     DeleteFileW(tmpbuf);
2087     return _wcsdup(tmpbuf);
2088   }
2089   TRACE("failed (%d)\n",GetLastError());
2090   return NULL;
2091 }
2092
2093 /*********************************************************************
2094  *              _umask (MSVCRT.@)
2095  */
2096 int CDECL MSVCRT__umask(int umask)
2097 {
2098   int old_umask = MSVCRT_umask;
2099   TRACE("(%d)\n",umask);
2100   MSVCRT_umask = umask;
2101   return old_umask;
2102 }
2103
2104 /*********************************************************************
2105  *              _utime64 (MSVCRT.@)
2106  */
2107 int CDECL _utime64(const char* path, struct MSVCRT___utimbuf64 *t)
2108 {
2109   int fd = MSVCRT__open(path, MSVCRT__O_WRONLY | MSVCRT__O_BINARY);
2110
2111   if (fd > 0)
2112   {
2113     int retVal = _futime64(fd, t);
2114     MSVCRT__close(fd);
2115     return retVal;
2116   }
2117   return -1;
2118 }
2119
2120 /*********************************************************************
2121  *              _utime32 (MSVCRT.@)
2122  */
2123 int CDECL _utime32(const char* path, struct MSVCRT___utimbuf32 *t)
2124 {
2125     struct MSVCRT___utimbuf64 t64;
2126     t64.actime = t->actime;
2127     t64.modtime = t->modtime;
2128     return _utime64( path, &t64 );
2129 }
2130
2131 /*********************************************************************
2132  *              _utime (MSVCRT.@)
2133  */
2134 #ifdef _WIN64
2135 int CDECL _utime(const char* path, struct MSVCRT___utimbuf64 *t)
2136 {
2137     return _utime64( path, t );
2138 }
2139 #else
2140 int CDECL _utime(const char* path, struct MSVCRT___utimbuf32 *t)
2141 {
2142     return _utime32( path, t );
2143 }
2144 #endif
2145
2146 /*********************************************************************
2147  *              _wutime64 (MSVCRT.@)
2148  */
2149 int CDECL _wutime64(const MSVCRT_wchar_t* path, struct MSVCRT___utimbuf64 *t)
2150 {
2151   int fd = _wopen(path, MSVCRT__O_WRONLY | MSVCRT__O_BINARY);
2152
2153   if (fd > 0)
2154   {
2155     int retVal = _futime64(fd, t);
2156     MSVCRT__close(fd);
2157     return retVal;
2158   }
2159   return -1;
2160 }
2161
2162 /*********************************************************************
2163  *              _wutime32 (MSVCRT.@)
2164  */
2165 int CDECL _wutime32(const MSVCRT_wchar_t* path, struct MSVCRT___utimbuf32 *t)
2166 {
2167     struct MSVCRT___utimbuf64 t64;
2168     t64.actime = t->actime;
2169     t64.modtime = t->modtime;
2170     return _wutime64( path, &t64 );
2171 }
2172
2173 /*********************************************************************
2174  *              _wutime (MSVCRT.@)
2175  */
2176 #ifdef _WIN64
2177 int CDECL _wutime(const MSVCRT_wchar_t* path, struct MSVCRT___utimbuf64 *t)
2178 {
2179     return _wutime64( path, t );
2180 }
2181 #else
2182 int CDECL _wutime(const MSVCRT_wchar_t* path, struct MSVCRT___utimbuf32 *t)
2183 {
2184     return _wutime32( path, t );
2185 }
2186 #endif
2187
2188 /*********************************************************************
2189  *              _write (MSVCRT.@)
2190  */
2191 int CDECL MSVCRT__write(int fd, const void* buf, unsigned int count)
2192 {
2193   DWORD num_written;
2194   HANDLE hand = msvcrt_fdtoh(fd);
2195
2196   /* Don't trace small writes, it gets *very* annoying */
2197 #if 0
2198   if (count > 32)
2199     TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
2200 #endif
2201   if (hand == INVALID_HANDLE_VALUE)
2202     {
2203       *MSVCRT__errno() = MSVCRT_EBADF;
2204       return -1;
2205     }
2206
2207   /* If appending, go to EOF */
2208   if (MSVCRT_fdesc[fd].wxflag & WX_APPEND)
2209     MSVCRT__lseek(fd, 0, FILE_END);
2210
2211   if (!(MSVCRT_fdesc[fd].wxflag & WX_TEXT))
2212     {
2213       if (WriteFile(hand, buf, count, &num_written, NULL)
2214           &&  (num_written == count))
2215         return num_written;
2216       TRACE("WriteFile (fd %d, hand %p) failed-last error (%d)\n", fd,
2217        hand, GetLastError());
2218       *MSVCRT__errno() = MSVCRT_ENOSPC;
2219     }
2220   else
2221   {
2222       unsigned int i, j, nr_lf;
2223       char *p = NULL;
2224       const char *q;
2225       const char *s = buf, *buf_start = buf;
2226       /* find number of \n ( without preceding \r ) */
2227       for ( nr_lf=0,i = 0; i <count; i++)
2228       {
2229           if (s[i]== '\n')
2230           {
2231               nr_lf++;
2232               /*if ((i >1) && (s[i-1] == '\r')) nr_lf--; */
2233           }
2234       }
2235       if (nr_lf)
2236       {
2237           if ((q = p = MSVCRT_malloc(count + nr_lf)))
2238           {
2239               for (s = buf, i = 0, j = 0; i < count; i++)
2240               {
2241                   if (s[i]== '\n')
2242                   {
2243                       p[j++] = '\r';
2244                       /*if ((i >1) && (s[i-1] == '\r'))j--;*/
2245                   }
2246                   p[j++] = s[i];
2247               }
2248           }
2249           else
2250           {
2251               FIXME("Malloc failed\n");
2252               nr_lf =0;
2253               q = buf;
2254           }
2255       }
2256       else
2257           q = buf;
2258
2259       if ((WriteFile(hand, q, count+nr_lf, &num_written, NULL) == 0 ) || (num_written != count+nr_lf))
2260       {
2261           TRACE("WriteFile (fd %d, hand %p) failed-last error (%d), num_written %d\n",
2262            fd, hand, GetLastError(), num_written);
2263           *MSVCRT__errno() = MSVCRT_ENOSPC;
2264           if(nr_lf)
2265               MSVCRT_free(p);
2266           return s - buf_start;
2267       }
2268       else
2269       {
2270           if(nr_lf)
2271               MSVCRT_free(p);
2272           return count;
2273       }
2274   }
2275   return -1;
2276 }
2277
2278 /*********************************************************************
2279  *              _putw (MSVCRT.@)
2280  */
2281 int CDECL MSVCRT__putw(int val, MSVCRT_FILE* file)
2282 {
2283   int len;
2284   len = MSVCRT__write(file->_file, &val, sizeof(val));
2285   if (len == sizeof(val)) return val;
2286   file->_flag |= MSVCRT__IOERR;
2287   return MSVCRT_EOF;
2288 }
2289
2290 /*********************************************************************
2291  *              fclose (MSVCRT.@)
2292  */
2293 int CDECL MSVCRT_fclose(MSVCRT_FILE* file)
2294 {
2295   int r, flag;
2296
2297   flag = file->_flag;
2298   MSVCRT_free(file->_tmpfname);
2299   file->_tmpfname = NULL;
2300   /* flush stdio buffers */
2301   if(file->_flag & MSVCRT__IOWRT)
2302       MSVCRT_fflush(file);
2303   if(file->_flag & MSVCRT__IOMYBUF)
2304       MSVCRT_free(file->_base);
2305
2306   r=MSVCRT__close(file->_file);
2307
2308   file->_flag = 0;
2309
2310   return ((r == -1) || (flag & MSVCRT__IOERR) ? MSVCRT_EOF : 0);
2311 }
2312
2313 /*********************************************************************
2314  *              feof (MSVCRT.@)
2315  */
2316 int CDECL MSVCRT_feof(MSVCRT_FILE* file)
2317 {
2318   return file->_flag & MSVCRT__IOEOF;
2319 }
2320
2321 /*********************************************************************
2322  *              ferror (MSVCRT.@)
2323  */
2324 int CDECL MSVCRT_ferror(MSVCRT_FILE* file)
2325 {
2326   return file->_flag & MSVCRT__IOERR;
2327 }
2328
2329 /*********************************************************************
2330  *              _filbuf (MSVCRT.@)
2331  */
2332 int CDECL MSVCRT__filbuf(MSVCRT_FILE* file)
2333 {
2334   /* Allocate buffer if needed */
2335   if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF) ) {
2336         msvcrt_alloc_buffer(file);
2337   }
2338   if(!(file->_flag & MSVCRT__IOREAD)) {
2339         if(file->_flag & MSVCRT__IORW) {
2340                 file->_flag |= MSVCRT__IOREAD;
2341         } else {
2342                 return MSVCRT_EOF;
2343         }
2344   }
2345   if(file->_flag & MSVCRT__IONBF) {
2346         unsigned char c;
2347         int r;
2348         if ((r = read_i(file->_file,&c,1)) != 1) {
2349             file->_flag |= (r == 0) ? MSVCRT__IOEOF : MSVCRT__IOERR;
2350             return MSVCRT_EOF;
2351         }
2352         return c;
2353   } else {
2354         file->_cnt = read_i(file->_file, file->_base, file->_bufsiz);
2355         if(file->_cnt<=0) {
2356             file->_flag |= (file->_cnt == 0) ? MSVCRT__IOEOF : MSVCRT__IOERR;
2357             file->_cnt = 0;
2358             return MSVCRT_EOF;
2359         }
2360         file->_cnt--;
2361         file->_ptr = file->_base+1;
2362         return *(unsigned char *)file->_base;
2363   }
2364 }
2365
2366 /*********************************************************************
2367  *              fgetc (MSVCRT.@)
2368  */
2369 int CDECL MSVCRT_fgetc(MSVCRT_FILE* file)
2370 {
2371   unsigned char *i;
2372   unsigned int j;
2373   if (file->_cnt>0) {
2374     file->_cnt--;
2375     i = (unsigned char *)file->_ptr++;
2376     j = *i;
2377   } else
2378     j = MSVCRT__filbuf(file);
2379   return j;
2380 }
2381
2382 /*********************************************************************
2383  *              _fgetchar (MSVCRT.@)
2384  */
2385 int CDECL _fgetchar(void)
2386 {
2387   return MSVCRT_fgetc(MSVCRT_stdin);
2388 }
2389
2390 /*********************************************************************
2391  *              fgets (MSVCRT.@)
2392  */
2393 char * CDECL MSVCRT_fgets(char *s, int size, MSVCRT_FILE* file)
2394 {
2395   int    cc = MSVCRT_EOF;
2396   char * buf_start = s;
2397
2398   TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
2399         file,file->_file,s,size);
2400
2401   while ((size >1) && (cc = MSVCRT_fgetc(file)) != MSVCRT_EOF && cc != '\n')
2402     {
2403       *s++ = (char)cc;
2404       size --;
2405     }
2406   if ((cc == MSVCRT_EOF) && (s == buf_start)) /* If nothing read, return 0*/
2407   {
2408     TRACE(":nothing read\n");
2409     return NULL;
2410   }
2411   if ((cc != MSVCRT_EOF) && (size > 1))
2412     *s++ = cc;
2413   *s = '\0';
2414   TRACE(":got %s\n", debugstr_a(buf_start));
2415   return buf_start;
2416 }
2417
2418 /*********************************************************************
2419  *              fgetwc (MSVCRT.@)
2420  *
2421  * In MSVCRT__O_TEXT mode, multibyte characters are read from the file, dropping
2422  * the CR from CR/LF combinations
2423  */
2424 MSVCRT_wint_t CDECL MSVCRT_fgetwc(MSVCRT_FILE* file)
2425 {
2426   char c;
2427
2428   if (!(MSVCRT_fdesc[file->_file].wxflag & WX_TEXT))
2429     {
2430       MSVCRT_wchar_t wc;
2431       unsigned int i;
2432       int j;
2433       char *chp, *wcp;
2434       wcp = (char *)&wc;
2435       for(i=0; i<sizeof(wc); i++)
2436       {
2437         if (file->_cnt>0) 
2438         {
2439           file->_cnt--;
2440           chp = file->_ptr++;
2441           wcp[i] = *chp;
2442         } 
2443         else
2444         {
2445           j = MSVCRT__filbuf(file);
2446           if(file->_cnt<=0)
2447           {
2448             file->_flag |= (file->_cnt == 0) ? MSVCRT__IOEOF : MSVCRT__IOERR;
2449             file->_cnt = 0;
2450             return MSVCRT_WEOF;
2451           }
2452           wcp[i] = j;
2453         }
2454       }
2455       return wc;
2456     }
2457     
2458   c = MSVCRT_fgetc(file);
2459   if ((MSVCRT___mb_cur_max > 1) && MSVCRT_isleadbyte(c))
2460     {
2461       FIXME("Treat Multibyte characters\n");
2462     }
2463   if (c == MSVCRT_EOF)
2464     return MSVCRT_WEOF;
2465   else
2466     return (MSVCRT_wint_t)c;
2467 }
2468
2469 /*********************************************************************
2470  *              _getw (MSVCRT.@)
2471  */
2472 int CDECL MSVCRT__getw(MSVCRT_FILE* file)
2473 {
2474   char *ch;
2475   int i, k;
2476   unsigned int j;
2477   ch = (char *)&i;
2478   for (j=0; j<sizeof(int); j++) {
2479     k = MSVCRT_fgetc(file);
2480     if (k == MSVCRT_EOF) {
2481       file->_flag |= MSVCRT__IOEOF;
2482       return EOF;
2483     }
2484     ch[j] = k;
2485   }
2486   return i;
2487 }
2488
2489 /*********************************************************************
2490  *              getwc (MSVCRT.@)
2491  */
2492 MSVCRT_wint_t CDECL MSVCRT_getwc(MSVCRT_FILE* file)
2493 {
2494   return MSVCRT_fgetwc(file);
2495 }
2496
2497 /*********************************************************************
2498  *              _fgetwchar (MSVCRT.@)
2499  */
2500 MSVCRT_wint_t CDECL _fgetwchar(void)
2501 {
2502   return MSVCRT_fgetwc(MSVCRT_stdin);
2503 }
2504
2505 /*********************************************************************
2506  *              getwchar (MSVCRT.@)
2507  */
2508 MSVCRT_wint_t CDECL MSVCRT_getwchar(void)
2509 {
2510   return _fgetwchar();
2511 }
2512
2513 /*********************************************************************
2514  *              fgetws (MSVCRT.@)
2515  */
2516 MSVCRT_wchar_t * CDECL MSVCRT_fgetws(MSVCRT_wchar_t *s, int size, MSVCRT_FILE* file)
2517 {
2518   int    cc = MSVCRT_WEOF;
2519   MSVCRT_wchar_t * buf_start = s;
2520
2521   TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
2522         file,file->_file,s,size);
2523
2524   while ((size >1) && (cc = MSVCRT_fgetwc(file)) != MSVCRT_WEOF && cc != '\n')
2525     {
2526       *s++ = (char)cc;
2527       size --;
2528     }
2529   if ((cc == MSVCRT_WEOF) && (s == buf_start)) /* If nothing read, return 0*/
2530   {
2531     TRACE(":nothing read\n");
2532     return NULL;
2533   }
2534   if ((cc != MSVCRT_WEOF) && (size > 1))
2535     *s++ = cc;
2536   *s = 0;
2537   TRACE(":got %s\n", debugstr_w(buf_start));
2538   return buf_start;
2539 }
2540
2541 /*********************************************************************
2542  *              fwrite (MSVCRT.@)
2543  */
2544 MSVCRT_size_t CDECL MSVCRT_fwrite(const void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
2545 {
2546   MSVCRT_size_t wrcnt=size * nmemb;
2547   int written = 0;
2548   if (size == 0)
2549       return 0;
2550   if(file->_cnt) {
2551         int pcnt=(file->_cnt>wrcnt)? wrcnt: file->_cnt;
2552         memcpy(file->_ptr, ptr, pcnt);
2553         file->_cnt -= pcnt;
2554         file->_ptr += pcnt;
2555         written = pcnt;
2556         wrcnt -= pcnt;
2557         ptr = (const char*)ptr + pcnt;
2558   } else if(!(file->_flag & MSVCRT__IOWRT)) {
2559         if(file->_flag & MSVCRT__IORW) {
2560                 file->_flag |= MSVCRT__IOWRT;
2561         } else
2562                 return 0;
2563   }
2564   if(wrcnt) {
2565         /* Flush buffer */
2566         int res=msvcrt_flush_buffer(file);
2567         if(!res) {
2568                 int pwritten = MSVCRT__write(file->_file, ptr, wrcnt);
2569                 if (pwritten <= 0)
2570                 {
2571                     file->_flag |= MSVCRT__IOERR;
2572                     pwritten=0;
2573                 }
2574                 written += pwritten;
2575         }
2576   }
2577   return written / size;
2578 }
2579
2580 /*********************************************************************
2581  *              fputwc (MSVCRT.@)
2582  */
2583 MSVCRT_wint_t CDECL MSVCRT_fputwc(MSVCRT_wint_t wc, MSVCRT_FILE* file)
2584 {
2585   MSVCRT_wchar_t mwc=wc;
2586   if (MSVCRT_fwrite( &mwc, sizeof(mwc), 1, file) != 1)
2587     return MSVCRT_WEOF;
2588   return wc;
2589 }
2590
2591 /*********************************************************************
2592  *              _fputwchar (MSVCRT.@)
2593  */
2594 MSVCRT_wint_t CDECL _fputwchar(MSVCRT_wint_t wc)
2595 {
2596   return MSVCRT_fputwc(wc, MSVCRT_stdout);
2597 }
2598
2599 /*********************************************************************
2600  *              _wfsopen (MSVCRT.@)
2601  */
2602 MSVCRT_FILE * CDECL MSVCRT__wfsopen(const MSVCRT_wchar_t *path, const MSVCRT_wchar_t *mode, int share)
2603 {
2604   MSVCRT_FILE* file;
2605   int open_flags, stream_flags, fd;
2606
2607   TRACE("(%s,%s)\n", debugstr_w(path), debugstr_w(mode));
2608
2609   /* map mode string to open() flags. "man fopen" for possibilities. */
2610   if (msvcrt_get_flags(mode, &open_flags, &stream_flags) == -1)
2611       return NULL;
2612
2613   LOCK_FILES();
2614   fd = MSVCRT__wsopen(path, open_flags, share, MSVCRT__S_IREAD | MSVCRT__S_IWRITE);
2615   if (fd < 0)
2616     file = NULL;
2617   else if ((file = msvcrt_alloc_fp()) && msvcrt_init_fp(file, fd, stream_flags)
2618    != -1)
2619     TRACE(":fd (%d) mode (%s) FILE* (%p)\n", fd, debugstr_w(mode), file);
2620   else if (file)
2621   {
2622     file->_flag = 0;
2623     file = NULL;
2624   }
2625
2626   TRACE(":got (%p)\n",file);
2627   if (fd >= 0 && !file)
2628     MSVCRT__close(fd);
2629   UNLOCK_FILES();
2630   return file;
2631 }
2632
2633 /*********************************************************************
2634  *              _fsopen (MSVCRT.@)
2635  */
2636 MSVCRT_FILE * CDECL MSVCRT__fsopen(const char *path, const char *mode, int share)
2637 {
2638     MSVCRT_FILE *ret;
2639     MSVCRT_wchar_t *pathW = NULL, *modeW = NULL;
2640
2641     if (path && !(pathW = msvcrt_wstrdupa(path))) return NULL;
2642     if (mode && !(modeW = msvcrt_wstrdupa(mode)))
2643     {
2644         MSVCRT_free(pathW);
2645         return NULL;
2646     }
2647
2648     ret = MSVCRT__wfsopen(pathW, modeW, share);
2649
2650     MSVCRT_free(pathW);
2651     MSVCRT_free(modeW);
2652     return ret;
2653 }
2654
2655 /*********************************************************************
2656  *              fopen (MSVCRT.@)
2657  */
2658 MSVCRT_FILE * CDECL MSVCRT_fopen(const char *path, const char *mode)
2659 {
2660     return MSVCRT__fsopen( path, mode, MSVCRT__SH_DENYNO );
2661 }
2662
2663 /*********************************************************************
2664  *              _wfopen (MSVCRT.@)
2665  */
2666 MSVCRT_FILE * CDECL MSVCRT__wfopen(const MSVCRT_wchar_t *path, const MSVCRT_wchar_t *mode)
2667 {
2668     return MSVCRT__wfsopen( path, mode, MSVCRT__SH_DENYNO );
2669 }
2670
2671 /* MSVCRT_fputc calls MSVCRT__flsbuf which calls MSVCRT_fputc */
2672 int CDECL MSVCRT__flsbuf(int c, MSVCRT_FILE* file);
2673
2674 /*********************************************************************
2675  *              fputc (MSVCRT.@)
2676  */
2677 int CDECL MSVCRT_fputc(int c, MSVCRT_FILE* file)
2678 {
2679   if(file->_cnt>0) {
2680     *file->_ptr++=c;
2681     file->_cnt--;
2682     if (c == '\n')
2683     {
2684       int res = msvcrt_flush_buffer(file);
2685       return res ? res : c;
2686     }
2687     else
2688       return c & 0xff;
2689   } else {
2690     return MSVCRT__flsbuf(c, file);
2691   }
2692 }
2693
2694 /*********************************************************************
2695  *              _flsbuf (MSVCRT.@)
2696  */
2697 int CDECL MSVCRT__flsbuf(int c, MSVCRT_FILE* file)
2698 {
2699   /* Flush output buffer */
2700   if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
2701         msvcrt_alloc_buffer(file);
2702   }
2703   if(!(file->_flag & MSVCRT__IOWRT)) {
2704         if(file->_flag & MSVCRT__IORW) {
2705                 file->_flag |= MSVCRT__IOWRT;
2706         } else {
2707                 return MSVCRT_EOF;
2708         }
2709   }
2710   if(file->_bufsiz) {
2711         int res=msvcrt_flush_buffer(file);
2712         return res?res : MSVCRT_fputc(c, file);
2713   } else {
2714         unsigned char cc=c;
2715         int len;
2716         /* set _cnt to 0 for unbuffered FILEs */
2717         file->_cnt = 0;
2718         len = MSVCRT__write(file->_file, &cc, 1);
2719         if (len == 1) return c & 0xff;
2720         file->_flag |= MSVCRT__IOERR;
2721         return MSVCRT_EOF;
2722   }
2723 }
2724
2725 /*********************************************************************
2726  *              _fputchar (MSVCRT.@)
2727  */
2728 int CDECL _fputchar(int c)
2729 {
2730   return MSVCRT_fputc(c, MSVCRT_stdout);
2731 }
2732
2733 /*********************************************************************
2734  *              fread (MSVCRT.@)
2735  */
2736 MSVCRT_size_t CDECL MSVCRT_fread(void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
2737 { MSVCRT_size_t rcnt=size * nmemb;
2738   MSVCRT_size_t read=0;
2739   int pread=0;
2740
2741   if(!rcnt)
2742         return 0;
2743
2744   /* first buffered data */
2745   if(file->_cnt>0) {
2746         int pcnt= (rcnt>file->_cnt)? file->_cnt:rcnt;
2747         memcpy(ptr, file->_ptr, pcnt);
2748         file->_cnt -= pcnt;
2749         file->_ptr += pcnt;
2750         read += pcnt ;
2751         rcnt -= pcnt ;
2752         ptr = (char*)ptr + pcnt;
2753   } else if(!(file->_flag & MSVCRT__IOREAD )) {
2754         if(file->_flag & MSVCRT__IORW) {
2755                 file->_flag |= MSVCRT__IOREAD;
2756         } else
2757             return 0;
2758   }
2759   while(rcnt>0)
2760   {
2761     int i;
2762     /* Fill the buffer on small reads.
2763      * TODO: Use a better buffering strategy.
2764      */
2765     if (!file->_cnt && size*nmemb <= MSVCRT_BUFSIZ/2 && !(file->_flag & MSVCRT__IONBF)) {
2766       if (file->_bufsiz == 0) {
2767         msvcrt_alloc_buffer(file);
2768       }
2769       file->_cnt = MSVCRT__read(file->_file, file->_base, file->_bufsiz);
2770       file->_ptr = file->_base;
2771       i = (file->_cnt<rcnt) ? file->_cnt : rcnt;
2772       /* If the buffer fill reaches eof but fread wouldn't, clear eof. */
2773       if (i > 0 && i < file->_cnt) {
2774         MSVCRT_fdesc[file->_file].wxflag &= ~WX_ATEOF;
2775         file->_flag &= ~MSVCRT__IOEOF;
2776       }
2777       if (i > 0) {
2778         memcpy(ptr, file->_ptr, i);
2779         file->_cnt -= i;
2780         file->_ptr += i;
2781       }
2782     } else {
2783       i = MSVCRT__read(file->_file,ptr, rcnt);
2784     }
2785     pread += i;
2786     rcnt -= i;
2787     ptr = (char *)ptr+i;
2788     /* expose feof condition in the flags
2789      * MFC tests file->_flag for feof, and doesn't call feof())
2790      */
2791     if ( MSVCRT_fdesc[file->_file].wxflag & WX_ATEOF)
2792         file->_flag |= MSVCRT__IOEOF;
2793     else if (i == -1)
2794     {
2795         file->_flag |= MSVCRT__IOERR;
2796         pread = 0;
2797         rcnt = 0;
2798     }
2799     if (i < 1) break;
2800   }
2801   read+=pread;
2802   return read / size;
2803 }
2804
2805 /*********************************************************************
2806  *              _wfreopen (MSVCRT.@)
2807  *
2808  */
2809 MSVCRT_FILE* CDECL _wfreopen(const MSVCRT_wchar_t *path, const MSVCRT_wchar_t *mode, MSVCRT_FILE* file)
2810 {
2811   int open_flags, stream_flags, fd;
2812
2813   TRACE(":path (%p) mode (%s) file (%p) fd (%d)\n", debugstr_w(path), debugstr_w(mode), file, file->_file);
2814
2815   LOCK_FILES();
2816   if (!file || ((fd = file->_file) < 0) || fd > MSVCRT_fdend)
2817     file = NULL;
2818   else
2819   {
2820     MSVCRT_fclose(file);
2821     /* map mode string to open() flags. "man fopen" for possibilities. */
2822     if (msvcrt_get_flags(mode, &open_flags, &stream_flags) == -1)
2823       file = NULL;
2824     else
2825     {
2826       fd = _wopen(path, open_flags, MSVCRT__S_IREAD | MSVCRT__S_IWRITE);
2827       if (fd < 0)
2828         file = NULL;
2829       else if (msvcrt_init_fp(file, fd, stream_flags) == -1)
2830       {
2831           file->_flag = 0;
2832           WARN(":failed-last error (%d)\n",GetLastError());
2833           msvcrt_set_errno(GetLastError());
2834           file = NULL;
2835       }
2836     }
2837   }
2838   UNLOCK_FILES();
2839   return file;
2840 }
2841
2842 /*********************************************************************
2843  *      freopen (MSVCRT.@)
2844  *
2845  */
2846 MSVCRT_FILE* CDECL MSVCRT_freopen(const char *path, const char *mode, MSVCRT_FILE* file)
2847 {
2848     MSVCRT_FILE *ret;
2849     MSVCRT_wchar_t *pathW = NULL, *modeW = NULL;
2850
2851     if (path && !(pathW = msvcrt_wstrdupa(path))) return NULL;
2852     if (mode && !(modeW = msvcrt_wstrdupa(mode)))
2853     {
2854         MSVCRT_free(pathW);
2855         return NULL;
2856     }
2857
2858     ret = _wfreopen(pathW, modeW, file);
2859
2860     MSVCRT_free(pathW);
2861     MSVCRT_free(modeW);
2862     return ret;
2863 }
2864
2865 /*********************************************************************
2866  *              fsetpos (MSVCRT.@)
2867  */
2868 int CDECL MSVCRT_fsetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
2869 {
2870   /* Note that all this has been lifted 'as is' from fseek */
2871   if(file->_flag & MSVCRT__IOWRT)
2872         msvcrt_flush_buffer(file);
2873
2874   /* Discard buffered input */
2875   file->_cnt = 0;
2876   file->_ptr = file->_base;
2877   
2878   /* Reset direction of i/o */
2879   if(file->_flag & MSVCRT__IORW) {
2880         file->_flag &= ~(MSVCRT__IOREAD|MSVCRT__IOWRT);
2881   }
2882
2883   return (MSVCRT__lseeki64(file->_file,*pos,SEEK_SET) == -1) ? -1 : 0;
2884 }
2885
2886 /*********************************************************************
2887  *              ftell (MSVCRT.@)
2888  */
2889 LONG CDECL MSVCRT_ftell(MSVCRT_FILE* file)
2890 {
2891   /* TODO: just call fgetpos and return lower half of result */
2892   int off=0;
2893   MSVCRT_long pos;
2894   pos = _tell(file->_file);
2895   if(pos == -1) return -1;
2896   if(file->_bufsiz)  {
2897         if( file->_flag & MSVCRT__IOWRT ) {
2898                 off = file->_ptr - file->_base;
2899         } else {
2900                 off = -file->_cnt;
2901                 if (MSVCRT_fdesc[file->_file].wxflag & WX_TEXT) {
2902                         /* Black magic correction for CR removal */
2903                         int i;
2904                         for (i=0; i<file->_cnt; i++) {
2905                                 if (file->_ptr[i] == '\n')
2906                                         off--;
2907                         }
2908                         /* Black magic when reading CR at buffer boundary*/
2909                         if(MSVCRT_fdesc[file->_file].wxflag & WX_READCR)
2910                           off--;
2911
2912                 }
2913         }
2914   }
2915   return off + pos;
2916 }
2917
2918 /*********************************************************************
2919  *              fgetpos (MSVCRT.@)
2920  */
2921 int CDECL MSVCRT_fgetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
2922 {
2923   int off=0;
2924   *pos = MSVCRT__lseeki64(file->_file,0,SEEK_CUR);
2925   if(*pos == -1) return -1;
2926   if(file->_bufsiz)  {
2927         if( file->_flag & MSVCRT__IOWRT ) {
2928                 off = file->_ptr - file->_base;
2929         } else {
2930                 off = -file->_cnt;
2931                 if (MSVCRT_fdesc[file->_file].wxflag & WX_TEXT) {
2932                         /* Black magic correction for CR removal */
2933                         int i;
2934                         for (i=0; i<file->_cnt; i++) {
2935                                 if (file->_ptr[i] == '\n')
2936                                         off--;
2937                         }
2938                         /* Black magic when reading CR at buffer boundary*/
2939                         if(MSVCRT_fdesc[file->_file].wxflag & WX_READCR)
2940                           off--;
2941                 }
2942         }
2943   }
2944   *pos += off;
2945   return 0;
2946 }
2947
2948 /*********************************************************************
2949  *              fputs (MSVCRT.@)
2950  */
2951 int CDECL MSVCRT_fputs(const char *s, MSVCRT_FILE* file)
2952 {
2953     MSVCRT_size_t i, len = strlen(s);
2954     if (!(MSVCRT_fdesc[file->_file].wxflag & WX_TEXT))
2955       return MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
2956     for (i=0; i<len; i++)
2957       if (MSVCRT_fputc(s[i], file) == MSVCRT_EOF) 
2958         return MSVCRT_EOF;
2959     return 0;
2960 }
2961
2962 /*********************************************************************
2963  *              fputws (MSVCRT.@)
2964  */
2965 int CDECL MSVCRT_fputws(const MSVCRT_wchar_t *s, MSVCRT_FILE* file)
2966 {
2967     MSVCRT_size_t i, len = strlenW(s);
2968     if (!(MSVCRT_fdesc[file->_file].wxflag & WX_TEXT))
2969       return MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
2970     for (i=0; i<len; i++)
2971       {
2972         if ((s[i] == '\n') && (MSVCRT_fputc('\r', file) == MSVCRT_EOF))
2973           return MSVCRT_WEOF;
2974         if (MSVCRT_fputwc(s[i], file) == MSVCRT_WEOF)
2975           return MSVCRT_WEOF; 
2976       }
2977     return 0;
2978 }
2979
2980 /*********************************************************************
2981  *              getchar (MSVCRT.@)
2982  */
2983 int CDECL MSVCRT_getchar(void)
2984 {
2985   return MSVCRT_fgetc(MSVCRT_stdin);
2986 }
2987
2988 /*********************************************************************
2989  *              getc (MSVCRT.@)
2990  */
2991 int CDECL MSVCRT_getc(MSVCRT_FILE* file)
2992 {
2993   return MSVCRT_fgetc(file);
2994 }
2995
2996 /*********************************************************************
2997  *              gets (MSVCRT.@)
2998  */
2999 char * CDECL MSVCRT_gets(char *buf)
3000 {
3001   int    cc;
3002   char * buf_start = buf;
3003
3004   for(cc = MSVCRT_fgetc(MSVCRT_stdin); cc != MSVCRT_EOF && cc != '\n';
3005       cc = MSVCRT_fgetc(MSVCRT_stdin))
3006   if(cc != '\r') *buf++ = (char)cc;
3007
3008   *buf = '\0';
3009
3010   TRACE("got '%s'\n", buf_start);
3011   return buf_start;
3012 }
3013
3014 /*********************************************************************
3015  *              _getws (MSVCRT.@)
3016  */
3017 MSVCRT_wchar_t* CDECL MSVCRT__getws(MSVCRT_wchar_t* buf)
3018 {
3019     MSVCRT_wint_t cc;
3020     MSVCRT_wchar_t* ws = buf;
3021
3022     for (cc = MSVCRT_fgetwc(MSVCRT_stdin); cc != MSVCRT_WEOF && cc != '\n';
3023          cc = MSVCRT_fgetwc(MSVCRT_stdin))
3024     {
3025         if (cc != '\r')
3026             *buf++ = (MSVCRT_wchar_t)cc;
3027     }
3028     *buf = '\0';
3029
3030     TRACE("got %s\n", debugstr_w(ws));
3031     return ws;
3032 }
3033
3034 /*********************************************************************
3035  *              putc (MSVCRT.@)
3036  */
3037 int CDECL MSVCRT_putc(int c, MSVCRT_FILE* file)
3038 {
3039   return MSVCRT_fputc(c, file);
3040 }
3041
3042 /*********************************************************************
3043  *              putchar (MSVCRT.@)
3044  */
3045 int CDECL MSVCRT_putchar(int c)
3046 {
3047   return MSVCRT_fputc(c, MSVCRT_stdout);
3048 }
3049
3050 /*********************************************************************
3051  *              puts (MSVCRT.@)
3052  */
3053 int CDECL MSVCRT_puts(const char *s)
3054 {
3055     MSVCRT_size_t len = strlen(s);
3056     if (MSVCRT_fwrite(s,sizeof(*s),len,MSVCRT_stdout) != len) return MSVCRT_EOF;
3057     return MSVCRT_fwrite("\n",1,1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
3058 }
3059
3060 /*********************************************************************
3061  *              _putws (MSVCRT.@)
3062  */
3063 int CDECL _putws(const MSVCRT_wchar_t *s)
3064 {
3065     static const MSVCRT_wchar_t nl = '\n';
3066     MSVCRT_size_t len = strlenW(s);
3067     if (MSVCRT_fwrite(s,sizeof(*s),len,MSVCRT_stdout) != len) return MSVCRT_EOF;
3068     return MSVCRT_fwrite(&nl,sizeof(nl),1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
3069 }
3070
3071 /*********************************************************************
3072  *              remove (MSVCRT.@)
3073  */
3074 int CDECL MSVCRT_remove(const char *path)
3075 {
3076   TRACE("(%s)\n",path);
3077   if (DeleteFileA(path))
3078     return 0;
3079   TRACE(":failed (%d)\n",GetLastError());
3080   msvcrt_set_errno(GetLastError());
3081   return -1;
3082 }
3083
3084 /*********************************************************************
3085  *              _wremove (MSVCRT.@)
3086  */
3087 int CDECL _wremove(const MSVCRT_wchar_t *path)
3088 {
3089   TRACE("(%s)\n",debugstr_w(path));
3090   if (DeleteFileW(path))
3091     return 0;
3092   TRACE(":failed (%d)\n",GetLastError());
3093   msvcrt_set_errno(GetLastError());
3094   return -1;
3095 }
3096
3097 /*********************************************************************
3098  *              rename (MSVCRT.@)
3099  */
3100 int CDECL MSVCRT_rename(const char *oldpath,const char *newpath)
3101 {
3102   TRACE(":from %s to %s\n",oldpath,newpath);
3103   if (MoveFileExA(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
3104     return 0;
3105   TRACE(":failed (%d)\n",GetLastError());
3106   msvcrt_set_errno(GetLastError());
3107   return -1;
3108 }
3109
3110 /*********************************************************************
3111  *              _wrename (MSVCRT.@)
3112  */
3113 int CDECL _wrename(const MSVCRT_wchar_t *oldpath,const MSVCRT_wchar_t *newpath)
3114 {
3115   TRACE(":from %s to %s\n",debugstr_w(oldpath),debugstr_w(newpath));
3116   if (MoveFileExW(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
3117     return 0;
3118   TRACE(":failed (%d)\n",GetLastError());
3119   msvcrt_set_errno(GetLastError());
3120   return -1;
3121 }
3122
3123 /*********************************************************************
3124  *              setvbuf (MSVCRT.@)
3125  */
3126 int CDECL MSVCRT_setvbuf(MSVCRT_FILE* file, char *buf, int mode, MSVCRT_size_t size)
3127 {
3128   /* TODO: Check if file busy */
3129   if(file->_bufsiz) {
3130         MSVCRT_free(file->_base);
3131         file->_bufsiz = 0;
3132         file->_cnt = 0;
3133   }
3134   if(mode == MSVCRT__IOFBF) {
3135         file->_flag &= ~MSVCRT__IONBF;
3136         file->_base = file->_ptr = buf;
3137         if(buf) {
3138                 file->_bufsiz = size;
3139         }
3140   } else {
3141         file->_flag |= MSVCRT__IONBF;
3142   }
3143   return 0;
3144 }
3145
3146 /*********************************************************************
3147  *              setbuf (MSVCRT.@)
3148  */
3149 void CDECL MSVCRT_setbuf(MSVCRT_FILE* file, char *buf)
3150 {
3151   MSVCRT_setvbuf(file, buf, buf ? MSVCRT__IOFBF : MSVCRT__IONBF, MSVCRT_BUFSIZ);
3152 }
3153
3154 /*********************************************************************
3155  *              tmpnam (MSVCRT.@)
3156  */
3157 char * CDECL MSVCRT_tmpnam(char *s)
3158 {
3159   static int unique;
3160   char tmpstr[16];
3161   char *p;
3162   int count;
3163   if (s == 0)
3164     s = MSVCRT_tmpname;
3165   msvcrt_int_to_base32(GetCurrentProcessId(), tmpstr);
3166   p = s + sprintf(s, "\\s%s.", tmpstr);
3167   for (count = 0; count < MSVCRT_TMP_MAX; count++)
3168   {
3169     msvcrt_int_to_base32(unique++, tmpstr);
3170     strcpy(p, tmpstr);
3171     if (GetFileAttributesA(s) == INVALID_FILE_ATTRIBUTES &&
3172         GetLastError() == ERROR_FILE_NOT_FOUND)
3173       break;
3174   }
3175   return s;
3176 }
3177
3178 /*********************************************************************
3179  *              tmpfile (MSVCRT.@)
3180  */
3181 MSVCRT_FILE* CDECL MSVCRT_tmpfile(void)
3182 {
3183   char *filename = MSVCRT_tmpnam(NULL);
3184   int fd;
3185   MSVCRT_FILE* file = NULL;
3186
3187   LOCK_FILES();
3188   fd = MSVCRT__open(filename, MSVCRT__O_CREAT | MSVCRT__O_BINARY | MSVCRT__O_RDWR | MSVCRT__O_TEMPORARY);
3189   if (fd != -1 && (file = msvcrt_alloc_fp()))
3190   {
3191     if (msvcrt_init_fp(file, fd, MSVCRT__O_RDWR) == -1)
3192     {
3193         file->_flag = 0;
3194         file = NULL;
3195     }
3196     else file->_tmpfname = _strdup(filename);
3197   }
3198   UNLOCK_FILES();
3199   return file;
3200 }
3201
3202 /*********************************************************************
3203  *              vfprintf (MSVCRT.@)
3204  */
3205 int CDECL MSVCRT_vfprintf(MSVCRT_FILE* file, const char *format, __ms_va_list valist)
3206 {
3207   char buf[2048], *mem = buf;
3208   int written, resize = sizeof(buf), retval;
3209   /* There are two conventions for vsnprintf failing:
3210    * Return -1 if we truncated, or
3211    * Return the number of bytes that would have been written
3212    * The code below handles both cases
3213    */
3214   while ((written = MSVCRT_vsnprintf(mem, resize, format, valist)) == -1 ||
3215           written > resize)
3216   {
3217     resize = (written == -1 ? resize * 2 : written + 1);
3218     if (mem != buf)
3219       MSVCRT_free (mem);
3220     if (!(mem = MSVCRT_malloc(resize)))
3221       return MSVCRT_EOF;
3222   }
3223   retval = MSVCRT_fwrite(mem, sizeof(*mem), written, file);
3224   if (mem != buf)
3225     MSVCRT_free (mem);
3226   return retval;
3227 }
3228
3229 /*********************************************************************
3230  *              vfwprintf (MSVCRT.@)
3231  * FIXME:
3232  * Is final char included in written (then resize is too big) or not
3233  * (then we must test for equality too)?
3234  */
3235 int CDECL MSVCRT_vfwprintf(MSVCRT_FILE* file, const MSVCRT_wchar_t *format, __ms_va_list valist)
3236 {
3237   MSVCRT_wchar_t buf[2048], *mem = buf;
3238   int written, resize = sizeof(buf) / sizeof(MSVCRT_wchar_t), retval;
3239   /* See vfprintf comments */
3240   while ((written = MSVCRT_vsnwprintf(mem, resize, format, valist)) == -1 ||
3241           written > resize)
3242   {
3243     resize = (written == -1 ? resize * 2 : written + sizeof(MSVCRT_wchar_t));
3244     if (mem != buf)
3245       MSVCRT_free (mem);
3246     if (!(mem = MSVCRT_malloc(resize*sizeof(*mem))))
3247       return MSVCRT_EOF;
3248   }
3249   retval = MSVCRT_fwrite(mem, sizeof(*mem), written, file);
3250   if (mem != buf)
3251     MSVCRT_free (mem);
3252   return retval;
3253 }
3254
3255 /*********************************************************************
3256  *              vprintf (MSVCRT.@)
3257  */
3258 int CDECL MSVCRT_vprintf(const char *format, __ms_va_list valist)
3259 {
3260   return MSVCRT_vfprintf(MSVCRT_stdout,format,valist);
3261 }
3262
3263 /*********************************************************************
3264  *              vwprintf (MSVCRT.@)
3265  */
3266 int CDECL MSVCRT_vwprintf(const MSVCRT_wchar_t *format, __ms_va_list valist)
3267 {
3268   return MSVCRT_vfwprintf(MSVCRT_stdout,format,valist);
3269 }
3270
3271 /*********************************************************************
3272  *              fprintf (MSVCRT.@)
3273  */
3274 int CDECL MSVCRT_fprintf(MSVCRT_FILE* file, const char *format, ...)
3275 {
3276     __ms_va_list valist;
3277     int res;
3278     __ms_va_start(valist, format);
3279     res = MSVCRT_vfprintf(file, format, valist);
3280     __ms_va_end(valist);
3281     return res;
3282 }
3283
3284 /*********************************************************************
3285  *              fwprintf (MSVCRT.@)
3286  */
3287 int CDECL MSVCRT_fwprintf(MSVCRT_FILE* file, const MSVCRT_wchar_t *format, ...)
3288 {
3289     __ms_va_list valist;
3290     int res;
3291     __ms_va_start(valist, format);
3292     res = MSVCRT_vfwprintf(file, format, valist);
3293     __ms_va_end(valist);
3294     return res;
3295 }
3296
3297 /*********************************************************************
3298  *              printf (MSVCRT.@)
3299  */
3300 int CDECL MSVCRT_printf(const char *format, ...)
3301 {
3302     __ms_va_list valist;
3303     int res;
3304     __ms_va_start(valist, format);
3305     res = MSVCRT_vfprintf(MSVCRT_stdout, format, valist);
3306     __ms_va_end(valist);
3307     return res;
3308 }
3309
3310 /*********************************************************************
3311  *              ungetc (MSVCRT.@)
3312  */
3313 int CDECL MSVCRT_ungetc(int c, MSVCRT_FILE * file)
3314 {
3315         if (c == MSVCRT_EOF)
3316                 return MSVCRT_EOF;
3317         if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
3318                 msvcrt_alloc_buffer(file);
3319                 file->_ptr++;
3320         }
3321         if(file->_ptr>file->_base) {
3322                 file->_ptr--;
3323                 *file->_ptr=c;
3324                 file->_cnt++;
3325                 MSVCRT_clearerr(file);
3326                 return c;
3327         }
3328         return MSVCRT_EOF;
3329 }
3330
3331 /*********************************************************************
3332  *              ungetwc (MSVCRT.@)
3333  */
3334 MSVCRT_wint_t CDECL MSVCRT_ungetwc(MSVCRT_wint_t wc, MSVCRT_FILE * file)
3335 {
3336         MSVCRT_wchar_t mwc = wc;
3337         char * pp = (char *)&mwc;
3338         int i;
3339         for(i=sizeof(MSVCRT_wchar_t)-1;i>=0;i--) {
3340                 if(pp[i] != MSVCRT_ungetc(pp[i],file))
3341                         return MSVCRT_WEOF;
3342         }
3343         return mwc;
3344 }
3345
3346 /*********************************************************************
3347  *              wprintf (MSVCRT.@)
3348  */
3349 int CDECL MSVCRT_wprintf(const MSVCRT_wchar_t *format, ...)
3350 {
3351     __ms_va_list valist;
3352     int res;
3353     __ms_va_start(valist, format);
3354     res = MSVCRT_vwprintf(format, valist);
3355     __ms_va_end(valist);
3356     return res;
3357 }
3358
3359 /*********************************************************************
3360  *              _getmaxstdio (MSVCRT.@)
3361  */
3362 int CDECL _getmaxstdio(void)
3363 {
3364     FIXME("stub, always returns 512\n");
3365     return 512;
3366 }
3367
3368 /*********************************************************************
3369  *              _setmaxstdio_ (MSVCRT.@)
3370  */
3371 int CDECL _setmaxstdio(int newmax)
3372 {
3373     int res;
3374     if( newmax > 2048)
3375       res = -1;
3376     else
3377       res = newmax;
3378     FIXME("stub: setting new maximum for number of simultaneously open files not implemented,returning %d\n",res);
3379     return res;
3380 }
3381
3382 /*********************************************************************
3383  *              __pioinfo (MSVCRT.@)
3384  * FIXME: see MSVCRT_MAX_FILES define.
3385  */
3386 ioinfo * MSVCRT___pioinfo[] = { /* array of pointers to ioinfo arrays [64] */
3387     &MSVCRT_fdesc[0 * 64], &MSVCRT_fdesc[1 * 64], &MSVCRT_fdesc[2 * 64],
3388     &MSVCRT_fdesc[3 * 64], &MSVCRT_fdesc[4 * 64], &MSVCRT_fdesc[5 * 64],
3389     &MSVCRT_fdesc[6 * 64], &MSVCRT_fdesc[7 * 64], &MSVCRT_fdesc[8 * 64],
3390     &MSVCRT_fdesc[9 * 64], &MSVCRT_fdesc[10 * 64], &MSVCRT_fdesc[11 * 64],
3391     &MSVCRT_fdesc[12 * 64], &MSVCRT_fdesc[13 * 64], &MSVCRT_fdesc[14 * 64],
3392     &MSVCRT_fdesc[15 * 64], &MSVCRT_fdesc[16 * 64], &MSVCRT_fdesc[17 * 64],
3393     &MSVCRT_fdesc[18 * 64], &MSVCRT_fdesc[19 * 64], &MSVCRT_fdesc[20 * 64],
3394     &MSVCRT_fdesc[21 * 64], &MSVCRT_fdesc[22 * 64], &MSVCRT_fdesc[23 * 64],
3395     &MSVCRT_fdesc[24 * 64], &MSVCRT_fdesc[25 * 64], &MSVCRT_fdesc[26 * 64],
3396     &MSVCRT_fdesc[27 * 64], &MSVCRT_fdesc[28 * 64], &MSVCRT_fdesc[29 * 64],
3397     &MSVCRT_fdesc[30 * 64], &MSVCRT_fdesc[31 * 64]
3398 } ;
3399
3400 /*********************************************************************
3401  *              __badioinfo (MSVCRT.@)
3402  */
3403 ioinfo MSVCRT___badioinfo = { INVALID_HANDLE_VALUE, WX_TEXT };