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