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