Fixed definitions of TTTOOLINFOA/W_V1_SIZE and
[wine] / dlls / msvcrt / file.c
1 /*
2  * msvcrt.dll file functions
3  *
4  * Copyright 1996,1998 Marcus Meissner
5  * Copyright 1996 Jukka Iivonen
6  * Copyright 1997,2000 Uwe Bonnes
7  * Copyright 2000 Jon Griffiths
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <time.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winreg.h"
37 #include "winternl.h"
38 #include "msvcrt.h"
39 #include "msvcrt/errno.h"
40
41 #include "wine/unicode.h"
42 #include "msvcrt/direct.h"
43 #include "msvcrt/fcntl.h"
44 #include "msvcrt/io.h"
45 #include "msvcrt/sys/locking.h"
46 #include "msvcrt/stdio.h"
47 #include "msvcrt/stdlib.h"
48 #include "msvcrt/string.h"
49 #include "msvcrt/sys/stat.h"
50 #include "msvcrt/sys/utime.h"
51 #include "msvcrt/time.h"
52 #include "msvcrt/share.h"
53 #include "msvcrt/wctype.h"
54
55 #include "wine/debug.h"
56
57 WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
58
59 /* for stat mode, permissions apply to all,owner and group */
60 #define MSVCRT_S_IREAD  (_S_IREAD  | (_S_IREAD  >> 3) | (_S_IREAD  >> 6))
61 #define MSVCRT_S_IWRITE (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6))
62 #define MSVCRT_S_IEXEC  (_S_IEXEC  | (_S_IEXEC  >> 3) | (_S_IEXEC  >> 6))
63
64 /* _access() bit flags FIXME: incomplete */
65 #define MSVCRT_W_OK      0x02
66
67
68 /* FIXME: Make this dynamic */
69 #define MSVCRT_MAX_FILES 257
70
71 HANDLE MSVCRT_handles[MSVCRT_MAX_FILES];
72 MSVCRT_FILE* MSVCRT_files[MSVCRT_MAX_FILES];
73 int  MSVCRT_flags[MSVCRT_MAX_FILES];
74 char *MSVCRT_tempfiles[MSVCRT_MAX_FILES];
75 MSVCRT_FILE MSVCRT__iob[3];
76 #define MSVCRT_stdin       (MSVCRT__iob+STDIN_FILENO)
77 #define MSVCRT_stdout      (MSVCRT__iob+STDOUT_FILENO)
78 #define MSVCRT_stderr      (MSVCRT__iob+STDERR_FILENO)
79
80 static int MSVCRT_fdstart = 3; /* first unallocated fd */
81 static int MSVCRT_fdend = 3; /* highest allocated fd */
82
83 /* INTERNAL: process umask */
84 static int MSVCRT_umask = 0;
85
86 /* INTERNAL: Static buffer for temp file name */
87 static char MSVCRT_tmpname[MAX_PATH];
88
89 static const unsigned int EXE = 'e' << 16 | 'x' << 8 | 'e';
90 static const unsigned int BAT = 'b' << 16 | 'a' << 8 | 't';
91 static const unsigned int CMD = 'c' << 16 | 'm' << 8 | 'd';
92 static const unsigned int COM = 'c' << 16 | 'o' << 8 | 'm';
93
94 #define TOUL(x) (ULONGLONG)(x)
95 static const ULONGLONG WCEXE = TOUL('e') << 32 | TOUL('x') << 16 | TOUL('e');
96 static const ULONGLONG WCBAT = TOUL('b') << 32 | TOUL('a') << 16 | TOUL('t');
97 static const ULONGLONG WCCMD = TOUL('c') << 32 | TOUL('m') << 16 | TOUL('d');
98 static const ULONGLONG WCCOM = TOUL('c') << 32 | TOUL('o') << 16 | TOUL('m');
99
100 extern CRITICAL_SECTION MSVCRT_file_cs;
101 #define LOCK_FILES     EnterCriticalSection(&MSVCRT_file_cs)
102 #define UNLOCK_FILES   LeaveCriticalSection(&MSVCRT_file_cs)
103
104 static void msvcrt_cp_from_stati64(const struct _stati64 *bufi64, struct _stat *buf)
105 {
106     buf->st_dev   = bufi64->st_dev;
107     buf->st_ino   = bufi64->st_ino;
108     buf->st_mode  = bufi64->st_mode;
109     buf->st_nlink = bufi64->st_nlink;
110     buf->st_uid   = bufi64->st_uid;
111     buf->st_gid   = bufi64->st_gid;
112     buf->st_rdev  = bufi64->st_rdev;
113     buf->st_size  = bufi64->st_size;
114     buf->st_atime = bufi64->st_atime;
115     buf->st_mtime = bufi64->st_mtime;
116     buf->st_ctime = bufi64->st_ctime;
117 }
118
119 /* INTERNAL: Get the HANDLE for a fd */
120 static HANDLE msvcrt_fdtoh(int fd)
121 {
122   if (fd < 0 || fd >= MSVCRT_fdend ||
123       MSVCRT_handles[fd] == INVALID_HANDLE_VALUE)
124   {
125     WARN(":fd (%d) - no handle!\n",fd);
126     *__doserrno() = 0;
127     *MSVCRT__errno() = MSVCRT_EBADF;
128    return INVALID_HANDLE_VALUE;
129   }
130   return MSVCRT_handles[fd];
131 }
132
133 /* INTERNAL: free a file entry fd */
134 static void msvcrt_free_fd(int fd)
135 {
136   MSVCRT_handles[fd] = INVALID_HANDLE_VALUE;
137   MSVCRT_files[fd] = 0;
138   MSVCRT_flags[fd] = 0;
139   TRACE(":fd (%d) freed\n",fd);
140   if (fd < 3)
141     return; /* dont use 0,1,2 for user files */
142   if (fd == MSVCRT_fdend - 1)
143     MSVCRT_fdend--;
144   if (fd < MSVCRT_fdstart)
145     MSVCRT_fdstart = fd;
146 }
147
148 /* INTERNAL: Allocate an fd slot from a Win32 HANDLE */
149 static int msvcrt_alloc_fd(HANDLE hand, int flag)
150 {
151   int fd = MSVCRT_fdstart;
152
153   TRACE(":handle (%p) allocating fd (%d)\n",hand,fd);
154   if (fd >= MSVCRT_MAX_FILES)
155   {
156     WARN(":files exhausted!\n");
157     return -1;
158   }
159   MSVCRT_handles[fd] = hand;
160   MSVCRT_flags[fd] = flag;
161
162   /* locate next free slot */
163   if (fd == MSVCRT_fdend)
164     MSVCRT_fdstart = ++MSVCRT_fdend;
165   else
166     while(MSVCRT_fdstart < MSVCRT_fdend &&
167           MSVCRT_handles[MSVCRT_fdstart] != INVALID_HANDLE_VALUE)
168       MSVCRT_fdstart++;
169
170   return fd;
171 }
172
173 /* INTERNAL: Allocate a FILE* for an fd slot
174  * This is done lazily to avoid memory wastage for low level open/write
175  * usage when a FILE* is not requested (but may be later).
176  */
177 static MSVCRT_FILE* msvcrt_alloc_fp(int fd)
178 {
179   TRACE(":fd (%d) allocating FILE*\n",fd);
180   if (fd < 0 || fd >= MSVCRT_fdend ||
181       MSVCRT_handles[fd] == INVALID_HANDLE_VALUE)
182   {
183     WARN(":invalid fd %d\n",fd);
184     *__doserrno() = 0;
185     *MSVCRT__errno() = MSVCRT_EBADF;
186     return NULL;
187   }
188   if (!MSVCRT_files[fd])
189   {
190     if ((MSVCRT_files[fd] = MSVCRT_calloc(sizeof(MSVCRT_FILE),1)))
191     {
192       MSVCRT_files[fd]->_file = fd;
193       MSVCRT_files[fd]->_flag = MSVCRT_flags[fd];
194       MSVCRT_files[fd]->_flag &= ~MSVCRT__IOAPPEND; /* mask out, see above */
195     }
196   }
197   TRACE(":got FILE* (%p)\n",MSVCRT_files[fd]);
198   return MSVCRT_files[fd];
199 }
200
201
202 /* INTERNAL: Set up stdin, stderr and stdout */
203 void msvcrt_init_io(void)
204 {
205   int i;
206   memset(MSVCRT__iob,0,3*sizeof(MSVCRT_FILE));
207   MSVCRT_handles[0] = GetStdHandle(STD_INPUT_HANDLE);
208   MSVCRT_flags[0] = MSVCRT__iob[0]._flag = MSVCRT__IOREAD;
209   MSVCRT_handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
210   MSVCRT_flags[1] = MSVCRT__iob[1]._flag = MSVCRT__IOWRT;
211   MSVCRT_handles[2] = GetStdHandle(STD_ERROR_HANDLE);
212   MSVCRT_flags[2] = MSVCRT__iob[2]._flag = MSVCRT__IOWRT;
213
214   TRACE(":handles (%p)(%p)(%p)\n",MSVCRT_handles[0],
215         MSVCRT_handles[1],MSVCRT_handles[2]);
216
217   for (i = 0; i < 3; i++)
218   {
219     /* FILE structs for stdin/out/err are static and never deleted */
220     MSVCRT_files[i] = &MSVCRT__iob[i];
221     MSVCRT__iob[i]._file = i;
222     MSVCRT_tempfiles[i] = NULL;
223   }
224 }
225
226 /* free everything on process exit */
227 void msvcrt_free_io(void)
228 {
229     _fcloseall();
230     _close(0);
231     _close(1);
232     _close(2);
233 }
234
235 /* INTERNAL: Flush stdio file buffer */
236 static int msvcrt_flush_buffer(MSVCRT_FILE* file)
237 {
238   if(file->_bufsiz) {
239         int cnt=file->_ptr-file->_base;
240         if(cnt>0 && _write(file->_file, file->_base, cnt) != cnt) {
241                 return MSVCRT_EOF;
242         }
243         file->_ptr=file->_base;
244         file->_cnt=file->_bufsiz;
245   }
246   return 0;
247 }
248
249 /* INTERNAL: Allocate stdio file buffer */
250 static void msvcrt_alloc_buffer(MSVCRT_FILE* file)
251 {
252         file->_base = MSVCRT_calloc(MSVCRT_BUFSIZ,1);
253         if(file->_base) {
254                 file->_bufsiz = MSVCRT_BUFSIZ;
255                 file->_flag |= MSVCRT__IOMYBUF;
256         } else {
257                 file->_base = (unsigned char *)(&file->_charbuf);
258                 /* put here 2 ??? */
259                 file->_bufsiz = sizeof(file->_charbuf);
260         }
261         file->_ptr = file->_base;
262         file->_cnt = 0;
263 }
264
265 /*********************************************************************
266  *              __p__iob(MSVCRT.@)
267  */
268 MSVCRT_FILE *__p__iob(void)
269 {
270  return &MSVCRT__iob[0];
271 }
272
273 /*********************************************************************
274  *              _access (MSVCRT.@)
275  */
276 int _access(const char *filename, int mode)
277 {
278   DWORD attr = GetFileAttributesA(filename);
279
280   TRACE("(%s,%d) %ld\n",filename,mode,attr);
281
282   if (!filename || attr == 0xffffffff)
283   {
284     MSVCRT__set_errno(GetLastError());
285     return -1;
286   }
287   if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
288   {
289     MSVCRT__set_errno(ERROR_ACCESS_DENIED);
290     return -1;
291   }
292   return 0;
293 }
294
295 /*********************************************************************
296  *              _waccess (MSVCRT.@)
297  */
298 int _waccess(const MSVCRT_wchar_t *filename, int mode)
299 {
300   DWORD attr = GetFileAttributesW(filename);
301
302   TRACE("(%s,%d) %ld\n",debugstr_w(filename),mode,attr);
303
304   if (!filename || attr == 0xffffffff)
305   {
306     MSVCRT__set_errno(GetLastError());
307     return -1;
308   }
309   if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
310   {
311     MSVCRT__set_errno(ERROR_ACCESS_DENIED);
312     return -1;
313   }
314   return 0;
315 }
316
317 /*********************************************************************
318  *              _chmod (MSVCRT.@)
319  */
320 int _chmod(const char *path, int flags)
321 {
322   DWORD oldFlags = GetFileAttributesA(path);
323
324   if (oldFlags != 0x0FFFFFFFF)
325   {
326     DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
327       oldFlags | FILE_ATTRIBUTE_READONLY;
328
329     if (newFlags == oldFlags || SetFileAttributesA(path, newFlags))
330       return 0;
331   }
332   MSVCRT__set_errno(GetLastError());
333   return -1;
334 }
335
336 /*********************************************************************
337  *              _wchmod (MSVCRT.@)
338  */
339 int _wchmod(const MSVCRT_wchar_t *path, int flags)
340 {
341   DWORD oldFlags = GetFileAttributesW(path);
342
343   if (oldFlags != 0x0FFFFFFFF)
344   {
345     DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
346       oldFlags | FILE_ATTRIBUTE_READONLY;
347
348     if (newFlags == oldFlags || SetFileAttributesW(path, newFlags))
349       return 0;
350   }
351   MSVCRT__set_errno(GetLastError());
352   return -1;
353 }
354
355 /*********************************************************************
356  *              _chsize (MSVCRT.@)
357  */
358 int _chsize(int fd, long size)
359 {
360     FIXME("(fd=%d, size=%ld): stub\n", fd, size);
361     return -1;
362 }
363
364 /*********************************************************************
365  *              _dup (MSVCRT.@)
366  */
367 int _dup(int od)
368 {
369     FIXME("(od=%d): stub\n", od);
370     return -1;
371 }
372
373 /*********************************************************************
374  *              _dup2 (MSVCRT.@)
375  */
376 int _dup2(int od, int nd)
377 {
378     FIXME("(od=%d, nd=%d): stub\n", od, nd);
379     return -1;
380 }
381
382 /*********************************************************************
383  *              _unlink (MSVCRT.@)
384  */
385 int _unlink(const char *path)
386 {
387   TRACE("(%s)\n",path);
388   if(DeleteFileA(path))
389     return 0;
390   TRACE("failed (%ld)\n",GetLastError());
391   MSVCRT__set_errno(GetLastError());
392   return -1;
393 }
394
395 /*********************************************************************
396  *              _wunlink (MSVCRT.@)
397  */
398 int _wunlink(const MSVCRT_wchar_t *path)
399 {
400   TRACE("(%s)\n",debugstr_w(path));
401   if(DeleteFileW(path))
402     return 0;
403   TRACE("failed (%ld)\n",GetLastError());
404   MSVCRT__set_errno(GetLastError());
405   return -1;
406 }
407
408 /*********************************************************************
409  *              _close (MSVCRT.@)
410  */
411 int _close(int fd)
412 {
413   HANDLE hand = msvcrt_fdtoh(fd);
414
415   TRACE(":fd (%d) handle (%p)\n",fd,hand);
416   if (hand == INVALID_HANDLE_VALUE)
417     return -1;
418   /* flush stdio buffers */
419   if(MSVCRT_files[fd]) {
420         if(MSVCRT_files[fd]->_flag & MSVCRT__IOWRT)
421                 MSVCRT_fflush(MSVCRT_files[fd]);
422
423         if(MSVCRT_files[fd]->_flag & MSVCRT__IOMYBUF)
424                 MSVCRT_free(MSVCRT_files[fd]->_base);
425   }
426
427   /* Dont free std FILE*'s, they are not dynamic */
428   if (fd > 2 && MSVCRT_files[fd])
429     MSVCRT_free(MSVCRT_files[fd]);
430
431   msvcrt_free_fd(fd);
432
433   if (!CloseHandle(hand))
434   {
435     WARN(":failed-last error (%ld)\n",GetLastError());
436     MSVCRT__set_errno(GetLastError());
437     return -1;
438   }
439   if (MSVCRT_tempfiles[fd])
440   {
441     TRACE("deleting temporary file '%s'\n",MSVCRT_tempfiles[fd]);
442     _unlink(MSVCRT_tempfiles[fd]);
443     MSVCRT_free(MSVCRT_tempfiles[fd]);
444     MSVCRT_tempfiles[fd] = NULL;
445   }
446
447   TRACE(":ok\n");
448   return 0;
449 }
450
451 /*********************************************************************
452  *              _commit (MSVCRT.@)
453  */
454 int _commit(int fd)
455 {
456   HANDLE hand = msvcrt_fdtoh(fd);
457
458   TRACE(":fd (%d) handle (%p)\n",fd,hand);
459   if (hand == INVALID_HANDLE_VALUE)
460     return -1;
461
462   if (!FlushFileBuffers(hand))
463   {
464     if (GetLastError() == ERROR_INVALID_HANDLE)
465     {
466       /* FlushFileBuffers fails for console handles
467        * so we ignore this error.
468        */
469       return 0;
470     }
471     TRACE(":failed-last error (%ld)\n",GetLastError());
472     MSVCRT__set_errno(GetLastError());
473     return -1;
474   }
475   TRACE(":ok\n");
476   return 0;
477 }
478
479 /*********************************************************************
480  *              _eof (MSVCRT.@)
481  */
482 int _eof(int fd)
483 {
484   DWORD curpos,endpos;
485   HANDLE hand = msvcrt_fdtoh(fd);
486
487   TRACE(":fd (%d) handle (%p)\n",fd,hand);
488
489   if (hand == INVALID_HANDLE_VALUE)
490     return -1;
491
492   /* If we have a FILE* for this file, the EOF flag
493    * will be set by the read()/write() functions.
494    */
495   if (MSVCRT_files[fd])
496     return MSVCRT_flags[fd] & MSVCRT__IOEOF;
497
498   /* Otherwise we do it the hard way */
499   curpos = SetFilePointer(hand, 0, NULL, SEEK_CUR);
500   endpos = SetFilePointer(hand, 0, NULL, FILE_END);
501
502   if (curpos == endpos)
503     return TRUE;
504
505   SetFilePointer(hand, curpos, 0, FILE_BEGIN);
506   return FALSE;
507 }
508
509 /*********************************************************************
510  *              _fcloseall (MSVCRT.@)
511  */
512 int _fcloseall(void)
513 {
514   int num_closed = 0, i;
515
516   for (i = 3; i < MSVCRT_fdend; i++)
517     if (MSVCRT_handles[i] != INVALID_HANDLE_VALUE)
518     {
519       _close(i);
520       num_closed++;
521     }
522
523   TRACE(":closed (%d) handles\n",num_closed);
524   return num_closed;
525 }
526
527 /*********************************************************************
528  *              _lseek (MSVCRT.@)
529  */
530 __int64 _lseeki64(int fd, __int64 offset, int whence)
531 {
532   DWORD ret, hoffset = (DWORD) (offset >> 32);
533   HANDLE hand = msvcrt_fdtoh(fd);
534
535   TRACE(":fd (%d) handle (%p)\n",fd,hand);
536   if (hand == INVALID_HANDLE_VALUE)
537     return -1;
538
539   if (whence < 0 || whence > 2)
540   {
541     *MSVCRT__errno() = MSVCRT_EINVAL;
542     return -1;
543   }
544
545   TRACE(":fd (%d) to 0x%08lx%08lx pos %s\n",
546         fd,hoffset,(long)offset,
547         (whence==SEEK_SET)?"SEEK_SET":
548         (whence==SEEK_CUR)?"SEEK_CUR":
549         (whence==SEEK_END)?"SEEK_END":"UNKNOWN");
550
551   if (((ret = SetFilePointer(hand, (long)offset, &hoffset,
552                              whence)) != INVALID_SET_FILE_POINTER) || !GetLastError())
553   {
554     if (MSVCRT_files[fd])
555       MSVCRT_files[fd]->_flag &= ~MSVCRT__IOEOF;
556     /* FIXME: What if we seek _to_ EOF - is EOF set? */
557
558     return ((__int64)hoffset << 32) | ret;
559   }
560   TRACE(":error-last error (%ld)\n",GetLastError());
561   if (MSVCRT_files[fd])
562     switch(GetLastError())
563     {
564     case ERROR_NEGATIVE_SEEK:
565     case ERROR_SEEK_ON_DEVICE:
566       MSVCRT__set_errno(GetLastError());
567       MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
568       break;
569     default:
570       break;
571     }
572   return -1;
573 }
574
575 /*********************************************************************
576  *              _lseek (MSVCRT.@)
577  */
578 LONG _lseek(int fd, LONG offset, int whence)
579 {
580     return _lseeki64(fd, offset, whence);
581 }
582
583 /*********************************************************************
584  *              _locking (MSVCRT.@)
585  *
586  * This is untested; the underlying LockFile doesn't work yet.
587  */
588 int _locking(int fd, int mode, LONG nbytes)
589 {
590   BOOL ret;
591   DWORD cur_locn;
592   HANDLE hand = msvcrt_fdtoh(fd);
593
594   TRACE(":fd (%d) handle (%p)\n",fd,hand);
595   if (hand == INVALID_HANDLE_VALUE)
596     return -1;
597
598   if (mode < 0 || mode > 4)
599   {
600     *MSVCRT__errno() = MSVCRT_EINVAL;
601     return -1;
602   }
603
604   TRACE(":fd (%d) by 0x%08lx mode %s\n",
605         fd,nbytes,(mode==_LK_UNLCK)?"_LK_UNLCK":
606         (mode==_LK_LOCK)?"_LK_LOCK":
607         (mode==_LK_NBLCK)?"_LK_NBLCK":
608         (mode==_LK_RLCK)?"_LK_RLCK":
609         (mode==_LK_NBRLCK)?"_LK_NBRLCK":
610                           "UNKNOWN");
611
612   if ((cur_locn = SetFilePointer(hand, 0L, NULL, SEEK_CUR)) == INVALID_SET_FILE_POINTER)
613   {
614     FIXME ("Seek failed\n");
615     *MSVCRT__errno() = MSVCRT_EINVAL; /* FIXME */
616     return -1;
617   }
618   if (mode == _LK_LOCK || mode == _LK_RLCK)
619   {
620     int nretry = 10;
621     ret = 1; /* just to satisfy gcc */
622     while (nretry--)
623     {
624       ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
625       if (ret) break;
626       sleep (1);
627     }
628   }
629   else if (mode == _LK_UNLCK)
630     ret = UnlockFile(hand, cur_locn, 0L, nbytes, 0L);
631   else
632     ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
633   /* FIXME - what about error settings? */
634   return ret ? 0 : -1;
635 }
636
637 /*********************************************************************
638  *              rewind (MSVCRT.@)
639  */
640 void MSVCRT_rewind(MSVCRT_FILE* file)
641 {
642   TRACE(":file (%p) fd (%d)\n",file,file->_file);
643   MSVCRT_fseek(file, 0L, SEEK_SET);
644   MSVCRT_clearerr(file);
645 }
646
647 /*********************************************************************
648  *              _fdopen (MSVCRT.@)
649  */
650 MSVCRT_FILE* _fdopen(int fd, const char *mode)
651 {
652   MSVCRT_FILE* file = msvcrt_alloc_fp(fd);
653
654   TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,mode,file);
655
656   return file;
657 }
658
659 /*********************************************************************
660  *              _wfdopen (MSVCRT.@)
661  */
662 MSVCRT_FILE* _wfdopen(int fd, const MSVCRT_wchar_t *mode)
663 {
664   MSVCRT_FILE* file = msvcrt_alloc_fp(fd);
665
666   TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,debugstr_w(mode),file);
667   if (file)
668     MSVCRT_rewind(file);
669
670   return file;
671 }
672
673 /*********************************************************************
674  *              _filelength (MSVCRT.@)
675  */
676 LONG _filelength(int fd)
677 {
678   LONG curPos = _lseek(fd, 0, SEEK_CUR);
679   if (curPos != -1)
680   {
681     LONG endPos = _lseek(fd, 0, SEEK_END);
682     if (endPos != -1)
683     {
684       if (endPos != curPos)
685         _lseek(fd, curPos, SEEK_SET);
686       return endPos;
687     }
688   }
689   return -1;
690 }
691
692 /*********************************************************************
693  *              _fileno (MSVCRT.@)
694  */
695 int _fileno(MSVCRT_FILE* file)
696 {
697   TRACE(":FILE* (%p) fd (%d)\n",file,file->_file);
698   return file->_file;
699 }
700
701 /*********************************************************************
702  *              _flushall (MSVCRT.@)
703  */
704 int _flushall(void)
705 {
706   int num_flushed = 0, i = 3;
707
708   while(i < MSVCRT_fdend)
709     if (MSVCRT_handles[i] != INVALID_HANDLE_VALUE)
710     {
711 #if 0
712       /* FIXME: flush, do not commit */
713       if (_commit(i) == -1)
714         if (MSVCRT_files[i])
715           MSVCRT_files[i]->_flag |= MSVCRT__IOERR;
716 #endif
717       if(MSVCRT_files[i] && MSVCRT_files[i]->_flag & MSVCRT__IOWRT) {
718         MSVCRT_fflush(MSVCRT_files[i]);
719         num_flushed++;
720       }
721     }
722
723   TRACE(":flushed (%d) handles\n",num_flushed);
724   return num_flushed;
725 }
726
727 /*********************************************************************
728  *              _fstati64 (MSVCRT.@)
729  */
730 int _fstati64(int fd, struct _stati64* buf)
731 {
732   DWORD dw;
733   BY_HANDLE_FILE_INFORMATION hfi;
734   HANDLE hand = msvcrt_fdtoh(fd);
735
736   TRACE(":fd (%d) stat (%p)\n",fd,buf);
737   if (hand == INVALID_HANDLE_VALUE)
738     return -1;
739
740   if (!buf)
741   {
742     WARN(":failed-NULL buf\n");
743     MSVCRT__set_errno(ERROR_INVALID_PARAMETER);
744     return -1;
745   }
746
747   memset(&hfi, 0, sizeof(hfi));
748   memset(buf, 0, sizeof(struct _stati64));
749   if (!GetFileInformationByHandle(hand, &hfi))
750   {
751     WARN(":failed-last error (%ld)\n",GetLastError());
752     MSVCRT__set_errno(ERROR_INVALID_PARAMETER);
753     return -1;
754   }
755   FIXME(":dwFileAttributes = %ld, mode set to 0\n",hfi.dwFileAttributes);
756   buf->st_nlink = hfi.nNumberOfLinks;
757   buf->st_size  = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
758   RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
759   buf->st_atime = dw;
760   RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
761   buf->st_mtime = buf->st_ctime = dw;
762   return 0;
763 }
764
765 /*********************************************************************
766  *              _fstat (MSVCRT.@)
767  */
768 int MSVCRT__fstat(int fd, struct _stat* buf)
769 { int ret;
770   struct _stati64 bufi64;
771
772   ret = _fstati64(fd, &bufi64);
773   if (!ret)
774       msvcrt_cp_from_stati64(&bufi64, buf);
775   return ret;
776 }
777
778 /*********************************************************************
779  *              _futime (MSVCRT.@)
780  */
781 int _futime(int fd, struct _utimbuf *t)
782 {
783   HANDLE hand = msvcrt_fdtoh(fd);
784   FILETIME at, wt;
785
786   if (!t)
787   {
788     MSVCRT_time_t currTime;
789     MSVCRT_time(&currTime);
790     RtlSecondsSince1970ToTime(currTime, (LARGE_INTEGER *)&at);
791     memcpy(&wt, &at, sizeof(wt));
792   }
793   else
794   {
795     RtlSecondsSince1970ToTime(t->actime, (LARGE_INTEGER *)&at);
796     if (t->actime == t->modtime)
797       memcpy(&wt, &at, sizeof(wt));
798     else
799       RtlSecondsSince1970ToTime(t->modtime, (LARGE_INTEGER *)&wt);
800   }
801
802   if (!SetFileTime(hand, NULL, &at, &wt))
803   {
804     MSVCRT__set_errno(GetLastError());
805     return -1 ;
806   }
807   return 0;
808 }
809
810 /*********************************************************************
811  *              _get_osfhandle (MSVCRT.@)
812  */
813 long _get_osfhandle(int fd)
814 {
815   HANDLE hand = msvcrt_fdtoh(fd);
816   HANDLE newhand = hand;
817   TRACE(":fd (%d) handle (%p)\n",fd,hand);
818
819   if (hand != INVALID_HANDLE_VALUE)
820   {
821     /* FIXME: I'm not convinced that I should be copying the
822      * handle here - it may be leaked if the app doesn't
823      * close it (and the API docs dont say that it should)
824      * Not duplicating it means that it can't be inherited
825      * and so lcc's wedit doesn't cope when it passes it to
826      * child processes. I've an idea that it should either
827      * be copied by CreateProcess, or marked as inheritable
828      * when initialised, or maybe both? JG 21-9-00.
829      */
830     DuplicateHandle(GetCurrentProcess(),hand,GetCurrentProcess(),
831                     &newhand,0,TRUE,DUPLICATE_SAME_ACCESS);
832   }
833   return (long)newhand;
834 }
835
836 /*********************************************************************
837  *              _isatty (MSVCRT.@)
838  */
839 int _isatty(int fd)
840 {
841   HANDLE hand = msvcrt_fdtoh(fd);
842
843   TRACE(":fd (%d) handle (%p)\n",fd,hand);
844   if (hand == INVALID_HANDLE_VALUE)
845     return 0;
846
847   return GetFileType(hand) == FILE_TYPE_CHAR? 1 : 0;
848 }
849
850 /*********************************************************************
851  *              _mktemp (MSVCRT.@)
852  */
853 char *_mktemp(char *pattern)
854 {
855   int numX = 0;
856   char *retVal = pattern;
857   int id;
858   char letter = 'a';
859
860   while(*pattern)
861     numX = (*pattern++ == 'X')? numX + 1 : 0;
862   if (numX < 5)
863     return NULL;
864   pattern--;
865   id = GetCurrentProcessId();
866   numX = 6;
867   while(numX--)
868   {
869     int tempNum = id / 10;
870     *pattern-- = id - (tempNum * 10) + '0';
871     id = tempNum;
872   }
873   pattern++;
874   do
875   {
876     if (GetFileAttributesA(retVal) == 0xFFFFFFFF &&
877         GetLastError() == ERROR_FILE_NOT_FOUND)
878       return retVal;
879     *pattern = letter++;
880   } while(letter != '|');
881   return NULL;
882 }
883
884 /*********************************************************************
885  *              _wmktemp (MSVCRT.@)
886  */
887 MSVCRT_wchar_t *_wmktemp(MSVCRT_wchar_t *pattern)
888 {
889   int numX = 0;
890   MSVCRT_wchar_t *retVal = pattern;
891   int id;
892   MSVCRT_wchar_t letter = 'a';
893
894   while(*pattern)
895     numX = (*pattern++ == 'X')? numX + 1 : 0;
896   if (numX < 5)
897     return NULL;
898   pattern--;
899   id = GetCurrentProcessId();
900   numX = 6;
901   while(numX--)
902   {
903     int tempNum = id / 10;
904     *pattern-- = id - (tempNum * 10) + '0';
905     id = tempNum;
906   }
907   pattern++;
908   do
909   {
910     if (GetFileAttributesW(retVal) == 0xFFFFFFFF &&
911         GetLastError() == ERROR_FILE_NOT_FOUND)
912       return retVal;
913     *pattern = letter++;
914   } while(letter != '|');
915   return NULL;
916 }
917
918 /*********************************************************************
919  *              _sopen (MSVCRT.@)
920  */
921 int MSVCRT__sopen( const char *path, int oflags, int shflags, ... )
922 {
923   va_list ap;
924   int pmode;
925   DWORD access = 0, creation = 0;
926   DWORD sharing;
927   int ioflag = 0, fd;
928   HANDLE hand;
929   SECURITY_ATTRIBUTES sa;
930
931
932   TRACE(":file (%s) oflags: 0x%04x shflags: 0x%04x\n",
933         path, oflags, shflags);
934
935   switch(oflags & (_O_RDONLY | _O_WRONLY | _O_RDWR))
936   {
937   case _O_RDONLY:
938     access |= GENERIC_READ;
939     ioflag |= MSVCRT__IOREAD;
940     break;
941   case _O_WRONLY:
942     access |= GENERIC_WRITE;
943     ioflag |= MSVCRT__IOWRT;
944     break;
945   case _O_RDWR:
946     access |= GENERIC_WRITE | GENERIC_READ;
947     ioflag |= MSVCRT__IORW;
948     break;
949   }
950
951   if (oflags & _O_CREAT)
952   {
953     va_start(ap, shflags);
954       pmode = va_arg(ap, int);
955     va_end(ap);
956
957     if(pmode & ~(_S_IREAD | _S_IWRITE))
958       FIXME(": pmode 0x%04x ignored\n", pmode);
959     else
960       WARN(": pmode 0x%04x ignored\n", pmode);
961
962     if (oflags & _O_EXCL)
963       creation = CREATE_NEW;
964     else if (oflags & _O_TRUNC)
965       creation = CREATE_ALWAYS;
966     else
967       creation = OPEN_ALWAYS;
968   }
969   else  /* no _O_CREAT */
970   {
971     if (oflags & _O_TRUNC)
972       creation = TRUNCATE_EXISTING;
973     else
974       creation = OPEN_EXISTING;
975   }
976   if (oflags & _O_APPEND)
977     ioflag |= MSVCRT__IOAPPEND;
978
979   if (oflags & _O_BINARY)
980     ioflag |= _O_BINARY;
981   else if (oflags & _O_TEXT)
982     ioflag |= _O_TEXT;
983   else if (*__p__fmode() & _O_BINARY)
984     ioflag |= _O_BINARY;
985   else
986     ioflag |= _O_TEXT; /* default to TEXT*/
987   
988   switch( shflags )
989   {
990     case _SH_DENYRW:
991       sharing = 0L;
992       break;
993     case _SH_DENYWR:
994       sharing = FILE_SHARE_READ;
995       break;
996     case _SH_DENYRD:
997       sharing = FILE_SHARE_WRITE;
998       break;
999     case _SH_DENYNO:
1000       sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
1001       break;
1002     default:
1003       ERR( "Unhandled shflags 0x%x\n", shflags );
1004       return -1;
1005   }
1006
1007   if (oflags & ~(_O_BINARY|_O_TEXT|_O_APPEND|_O_TRUNC|_O_EXCL
1008                 |_O_CREAT|_O_RDWR|_O_TEMPORARY|_O_NOINHERIT))
1009     TRACE(":unsupported oflags 0x%04x\n",oflags);
1010
1011   sa.nLength              = sizeof( SECURITY_ATTRIBUTES );
1012   sa.lpSecurityDescriptor = NULL;
1013   sa.bInheritHandle       = (oflags & _O_NOINHERIT) ? FALSE : TRUE;
1014
1015   hand = CreateFileA(path, access, sharing,
1016                       &sa, creation, FILE_ATTRIBUTE_NORMAL, 0);
1017
1018   if (hand == INVALID_HANDLE_VALUE)  {
1019     WARN(":failed-last error (%ld)\n",GetLastError());
1020     MSVCRT__set_errno(GetLastError());
1021     return -1;
1022   }
1023
1024   fd = msvcrt_alloc_fd(hand, ioflag);
1025
1026   TRACE(":fd (%d) handle (%p)\n",fd, hand);
1027
1028   if (fd > 0)
1029   {
1030     if (oflags & _O_TEMPORARY)
1031       MSVCRT_tempfiles[fd] = _strdup(path);
1032     if (ioflag & MSVCRT__IOAPPEND)
1033       _lseek(fd, 0, FILE_END);
1034   }
1035
1036   return fd;
1037 }
1038
1039 /*********************************************************************
1040  *              _wsopen (MSVCRT.@)
1041  */
1042 int MSVCRT__wsopen( const MSVCRT_wchar_t* path, int oflags, int shflags, ... )
1043 {
1044   const unsigned int len = strlenW(path);
1045   char *patha = MSVCRT_calloc(len + 1,1);
1046   va_list ap;
1047   int pmode;
1048
1049   va_start(ap, shflags);
1050   pmode = va_arg(ap, int);
1051   va_end(ap);
1052
1053   if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
1054   {
1055     int retval = MSVCRT__sopen(patha,oflags,shflags,pmode);
1056     MSVCRT_free(patha);
1057     return retval;
1058   }
1059
1060   MSVCRT__set_errno(GetLastError());
1061   return -1;
1062 }
1063
1064 /*********************************************************************
1065  *              _open (MSVCRT.@)
1066  */
1067 int _open( const char *path, int flags, ... )
1068 {
1069   va_list ap;
1070
1071   if (flags & _O_CREAT)
1072   {
1073     int pmode;
1074     va_start(ap, flags);
1075     pmode = va_arg(ap, int);
1076     va_end(ap);
1077     return MSVCRT__sopen( path, flags, _SH_DENYNO, pmode );
1078   }
1079   else
1080     return MSVCRT__sopen( path, flags, _SH_DENYNO);
1081 }
1082
1083 /*********************************************************************
1084  *              _wopen (MSVCRT.@)
1085  */
1086 int _wopen(const MSVCRT_wchar_t *path,int flags,...)
1087 {
1088   const unsigned int len = strlenW(path);
1089   char *patha = MSVCRT_calloc(len + 1,1);
1090   va_list ap;
1091   int pmode;
1092
1093   va_start(ap, flags);
1094   pmode = va_arg(ap, int);
1095   va_end(ap);
1096
1097   if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
1098   {
1099     int retval = _open(patha,flags,pmode);
1100     MSVCRT_free(patha);
1101     return retval;
1102   }
1103
1104   MSVCRT__set_errno(GetLastError());
1105   return -1;
1106 }
1107
1108 /*********************************************************************
1109  *              _creat (MSVCRT.@)
1110  */
1111 int _creat(const char *path, int flags)
1112 {
1113   int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
1114   return _open(path, usedFlags);
1115 }
1116
1117 /*********************************************************************
1118  *              _wcreat (MSVCRT.@)
1119  */
1120 int _wcreat(const MSVCRT_wchar_t *path, int flags)
1121 {
1122   int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
1123   return _wopen(path, usedFlags);
1124 }
1125
1126 /*********************************************************************
1127  *              _open_osfhandle (MSVCRT.@)
1128  */
1129 int _open_osfhandle(long hand, int flags)
1130 {
1131   int fd;
1132
1133   /* _O_RDONLY (0) always matches, so set the read flag
1134    * MFC's CStdioFile clears O_RDONLY (0)! if it wants to write to the
1135    * file, so set the write flag. It also only sets _O_TEXT if it wants
1136    * text - it never sets _O_BINARY.
1137    */
1138   /* FIXME: handle more flags */
1139   flags |= MSVCRT__IOREAD|MSVCRT__IOWRT;
1140   if ( !( flags & _O_TEXT ) ) flags |= _O_BINARY;
1141
1142   fd = msvcrt_alloc_fd((HANDLE)hand,flags);
1143   TRACE(":handle (%ld) fd (%d) flags 0x%08x\n",hand,fd, flags);
1144   return fd;
1145 }
1146
1147 /*********************************************************************
1148  *              _rmtmp (MSVCRT.@)
1149  */
1150 int _rmtmp(void)
1151 {
1152   int num_removed = 0, i;
1153
1154   for (i = 3; i < MSVCRT_fdend; i++)
1155     if (MSVCRT_tempfiles[i])
1156     {
1157       _close(i);
1158       num_removed++;
1159     }
1160
1161   if (num_removed)
1162     TRACE(":removed (%d) temp files\n",num_removed);
1163   return num_removed;
1164 }
1165
1166 /*********************************************************************
1167  *              _read (MSVCRT.@)
1168  */
1169 int _read(int fd, void *buf, unsigned int count)
1170 {
1171   DWORD num_read;
1172   HANDLE hand = msvcrt_fdtoh(fd);
1173
1174   /* Dont trace small reads, it gets *very* annoying */
1175   if (count > 4)
1176     TRACE(":fd (%d) handle (%p) buf (%p) len (%d)\n",fd,hand,buf,count);
1177   if (hand == INVALID_HANDLE_VALUE)
1178     return -1;
1179
1180   if (MSVCRT_flags[fd]& _O_BINARY)
1181     {
1182       if (ReadFile(hand, buf, count, &num_read, NULL))
1183         {
1184           if (num_read != count && MSVCRT_files[fd])
1185             {
1186               TRACE(":EOF\n");
1187               MSVCRT_flags[fd] |= MSVCRT__IOEOF;
1188               /*
1189                 MSVCRT_files[fd]->_flag |= MSVCRT__IOEOF;
1190               */
1191             }
1192           TRACE("%s\n",debugstr_an(buf,num_read));
1193           return num_read;
1194         }
1195       TRACE(":failed-last error (%ld)\n",GetLastError());
1196       if (MSVCRT_files[fd])
1197         MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
1198       return -1;
1199     }
1200   else
1201     {
1202       char cc, *s=(char*)buf,* buf_start=(char*)buf;
1203       unsigned int i;
1204       
1205       for (i = 0 , num_read = 1; i < count && (num_read == 1);)
1206         {
1207           if (ReadFile(hand, &cc, 1, &num_read, NULL))
1208             if (num_read == 1)
1209               if ((cc != '\r') || MSVCRT_flags[fd] & _O_BINARY)
1210                 {
1211                   *s++ = (char)cc;
1212                   i++;
1213                 }
1214         }
1215       if (num_read != 1)
1216         {
1217           TRACE(":EOF\n");
1218           if (MSVCRT_files[fd])
1219             MSVCRT_flags[fd] |= MSVCRT__IOEOF;
1220           /*
1221             MSVCRT_files[fd]->_flag |= MSVCRT__IOEOF;
1222           */
1223         }
1224   
1225       if (count > 4)
1226         TRACE("%s\n",debugstr_an(buf_start, s-buf_start));
1227       return s-buf_start;
1228     }
1229   return 0;
1230 }
1231
1232 /*********************************************************************
1233  *              _getw (MSVCRT.@)
1234  */
1235 int _getw(MSVCRT_FILE* file)
1236 {
1237   int i;
1238   if (_read(file->_file, &i, sizeof(int)) != 1)
1239     return MSVCRT_EOF;
1240   return i;
1241 }
1242
1243 /*********************************************************************
1244  *              _setmode (MSVCRT.@)
1245  */
1246 int _setmode(int fd,int mode)
1247 {
1248   int ret = MSVCRT_flags[fd] & (_O_TEXT | _O_BINARY);
1249   if (mode & (~(_O_TEXT|_O_BINARY)))
1250     FIXME("fd (%d) mode (0x%08x) unknown\n",fd,mode);
1251   MSVCRT_flags[fd] &= ~(_O_TEXT|_O_BINARY);
1252   MSVCRT_flags[fd] |= mode & (_O_TEXT | _O_BINARY);
1253   return ret;
1254 }
1255
1256 /*********************************************************************
1257  *              _stati64 (MSVCRT.@)
1258  */
1259 int _stati64(const char* path, struct _stati64 * buf)
1260 {
1261   DWORD dw;
1262   WIN32_FILE_ATTRIBUTE_DATA hfi;
1263   unsigned short mode = MSVCRT_S_IREAD;
1264   int plen;
1265
1266   TRACE(":file (%s) buf(%p)\n",path,buf);
1267
1268   if (!GetFileAttributesExA(path, GetFileExInfoStandard, &hfi))
1269   {
1270       TRACE("failed (%ld)\n",GetLastError());
1271       MSVCRT__set_errno(ERROR_FILE_NOT_FOUND);
1272       return -1;
1273   }
1274
1275   memset(buf,0,sizeof(struct _stati64));
1276
1277   /* FIXME: rdev isnt drive num,despite what the docs say-what is it?
1278      Bon 011120: This FIXME seems incorrect
1279                  Also a letter as first char isn't enough to be classify
1280                  as drive letter
1281   */
1282   if (isalpha(*path)&& (*(path+1)==':'))
1283     buf->st_dev = buf->st_rdev = toupper(*path) - 'A'; /* drive num */
1284   else
1285     buf->st_dev = buf->st_rdev = _getdrive() - 1;
1286
1287   plen = strlen(path);
1288
1289   /* Dir, or regular file? */
1290   if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1291       (path[plen-1] == '\\'))
1292     mode |= (_S_IFDIR | MSVCRT_S_IEXEC);
1293   else
1294   {
1295     mode |= _S_IFREG;
1296     /* executable? */
1297     if (plen > 6 && path[plen-4] == '.')  /* shortest exe: "\x.exe" */
1298     {
1299       unsigned int ext = tolower(path[plen-1]) | (tolower(path[plen-2]) << 8) |
1300                                  (tolower(path[plen-3]) << 16);
1301       if (ext == EXE || ext == BAT || ext == CMD || ext == COM)
1302           mode |= MSVCRT_S_IEXEC;
1303     }
1304   }
1305
1306   if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1307     mode |= MSVCRT_S_IWRITE;
1308
1309   buf->st_mode  = mode;
1310   buf->st_nlink = 1;
1311   buf->st_size  = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
1312   RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
1313   buf->st_atime = dw;
1314   RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
1315   buf->st_mtime = buf->st_ctime = dw;
1316   TRACE("%d %d 0x%08lx%08lx %ld %ld %ld\n", buf->st_mode,buf->st_nlink,
1317         (long)(buf->st_size >> 32),(long)buf->st_size,
1318         buf->st_atime,buf->st_mtime, buf->st_ctime);
1319   return 0;
1320 }
1321
1322 /*********************************************************************
1323  *              _stat (MSVCRT.@)
1324  */
1325 int MSVCRT__stat(const char* path, struct _stat * buf)
1326 { int ret;
1327   struct _stati64 bufi64;
1328
1329   ret = _stati64( path, &bufi64);
1330   if (!ret)
1331       msvcrt_cp_from_stati64(&bufi64, buf);
1332   return ret;
1333 }
1334
1335 /*********************************************************************
1336  *              _wstat (MSVCRT.@)
1337  */
1338 int _wstat(const MSVCRT_wchar_t* path, struct _stat * buf)
1339 {
1340   DWORD dw;
1341   WIN32_FILE_ATTRIBUTE_DATA hfi;
1342   unsigned short mode = MSVCRT_S_IREAD;
1343   int plen;
1344
1345   TRACE(":file (%s) buf(%p)\n",debugstr_w(path),buf);
1346
1347   if (!GetFileAttributesExW(path, GetFileExInfoStandard, &hfi))
1348   {
1349       TRACE("failed (%ld)\n",GetLastError());
1350       MSVCRT__set_errno(ERROR_FILE_NOT_FOUND);
1351       return -1;
1352   }
1353
1354   memset(buf,0,sizeof(struct _stat));
1355
1356   /* FIXME: rdev isn't drive num, despite what the docs says-what is it? */
1357   if (MSVCRT_iswalpha(*path))
1358     buf->st_dev = buf->st_rdev = toupperW(*path - 'A'); /* drive num */
1359   else
1360     buf->st_dev = buf->st_rdev = _getdrive() - 1;
1361
1362   plen = strlenW(path);
1363
1364   /* Dir, or regular file? */
1365   if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1366       (path[plen-1] == '\\'))
1367     mode |= (_S_IFDIR | MSVCRT_S_IEXEC);
1368   else
1369   {
1370     mode |= _S_IFREG;
1371     /* executable? */
1372     if (plen > 6 && path[plen-4] == '.')  /* shortest exe: "\x.exe" */
1373     {
1374       ULONGLONG ext = tolowerW(path[plen-1]) | (tolowerW(path[plen-2]) << 16) |
1375                                ((ULONGLONG)tolowerW(path[plen-3]) << 32);
1376       if (ext == WCEXE || ext == WCBAT || ext == WCCMD || ext == WCCOM)
1377         mode |= MSVCRT_S_IEXEC;
1378     }
1379   }
1380
1381   if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1382     mode |= MSVCRT_S_IWRITE;
1383
1384   buf->st_mode  = mode;
1385   buf->st_nlink = 1;
1386   buf->st_size  = hfi.nFileSizeLow;
1387   RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
1388   buf->st_atime = dw;
1389   RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
1390   buf->st_mtime = buf->st_ctime = dw;
1391   TRACE("\n%d %d %d %ld %ld %ld\n", buf->st_mode,buf->st_nlink,buf->st_size,
1392         buf->st_atime,buf->st_mtime, buf->st_ctime);
1393   return 0;
1394 }
1395
1396 /*********************************************************************
1397  *              _tell (MSVCRT.@)
1398  */
1399 LONG _tell(int fd)
1400 {
1401   return _lseek(fd, 0, SEEK_CUR);
1402 }
1403
1404 /*********************************************************************
1405  *              _tempnam (MSVCRT.@)
1406  */
1407 char *_tempnam(const char *dir, const char *prefix)
1408 {
1409   char tmpbuf[MAX_PATH];
1410
1411   TRACE("dir (%s) prefix (%s)\n",dir,prefix);
1412   if (GetTempFileNameA(dir,prefix,0,tmpbuf))
1413   {
1414     TRACE("got name (%s)\n",tmpbuf);
1415     return _strdup(tmpbuf);
1416   }
1417   TRACE("failed (%ld)\n",GetLastError());
1418   return NULL;
1419 }
1420
1421 /*********************************************************************
1422  *              _wtempnam (MSVCRT.@)
1423  */
1424 MSVCRT_wchar_t *_wtempnam(const MSVCRT_wchar_t *dir, const MSVCRT_wchar_t *prefix)
1425 {
1426   MSVCRT_wchar_t tmpbuf[MAX_PATH];
1427
1428   TRACE("dir (%s) prefix (%s)\n",debugstr_w(dir),debugstr_w(prefix));
1429   if (GetTempFileNameW(dir,prefix,0,tmpbuf))
1430   {
1431     TRACE("got name (%s)\n",debugstr_w(tmpbuf));
1432     return _wcsdup(tmpbuf);
1433   }
1434   TRACE("failed (%ld)\n",GetLastError());
1435   return NULL;
1436 }
1437
1438 /*********************************************************************
1439  *              _umask (MSVCRT.@)
1440  */
1441 int _umask(int umask)
1442 {
1443   int old_umask = MSVCRT_umask;
1444   TRACE("(%d)\n",umask);
1445   MSVCRT_umask = umask;
1446   return old_umask;
1447 }
1448
1449 /*********************************************************************
1450  *              _utime (MSVCRT.@)
1451  */
1452 int _utime(const char* path, struct _utimbuf *t)
1453 {
1454   int fd = _open(path, _O_WRONLY | _O_BINARY);
1455
1456   if (fd > 0)
1457   {
1458     int retVal = _futime(fd, t);
1459     _close(fd);
1460     return retVal;
1461   }
1462   return -1;
1463 }
1464
1465 /*********************************************************************
1466  *              _wutime (MSVCRT.@)
1467  */
1468 int _wutime(const MSVCRT_wchar_t* path, struct _utimbuf *t)
1469 {
1470   int fd = _wopen(path, _O_WRONLY | _O_BINARY);
1471
1472   if (fd > 0)
1473   {
1474     int retVal = _futime(fd, t);
1475     _close(fd);
1476     return retVal;
1477   }
1478   return -1;
1479 }
1480
1481 /*********************************************************************
1482  *              _write (MSVCRT.@)
1483  */
1484 int _write(int fd, const void* buf, unsigned int count)
1485 {
1486   DWORD num_written;
1487   HANDLE hand = msvcrt_fdtoh(fd);
1488
1489   /* Dont trace small writes, it gets *very* annoying */
1490 #if 0
1491   if (count > 32)
1492     TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
1493 #endif
1494   if (hand == INVALID_HANDLE_VALUE)
1495     {
1496       *MSVCRT__errno() = MSVCRT_EBADF;
1497       return -1;
1498     }
1499
1500   /* If appending, go to EOF */
1501   if (MSVCRT_flags[fd] & MSVCRT__IOAPPEND)
1502     _lseek(fd, 0, FILE_END);
1503
1504   if (MSVCRT_flags[fd] & _O_BINARY)
1505     {
1506       if (WriteFile(hand, buf, count, &num_written, NULL)
1507           &&  (num_written == count))
1508         return num_written;
1509       TRACE(":failed-last error (%ld)\n",GetLastError());
1510       if (MSVCRT_files[fd])
1511         {
1512           MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
1513           *MSVCRT__errno() = MSVCRT_ENOSPC;
1514         }
1515     }
1516   else
1517     {
1518       char *s=(char*)buf, *buf_start=(char*)buf, *p;
1519       char crlf[]= {'\r','\n'};
1520       unsigned int i;
1521       DWORD num_to_write;
1522       for (i = 0; i< count && !(MSVCRT_flags[fd] & MSVCRT__IOERR);i++, s++)
1523         {
1524           if (*s == '\n')
1525             {
1526               p = crlf;
1527               num_to_write = 2;
1528             }
1529           else
1530             { 
1531               p = s;
1532               num_to_write = 1;
1533             }
1534           if ((WriteFile(hand, p, num_to_write, &num_written, NULL) == 0 ) || (num_written != num_to_write))
1535             {
1536               TRACE(":failed-last error (%ld) num_written %ld\n",GetLastError(),num_written);
1537               if (MSVCRT_files[fd])
1538                 {
1539                   MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
1540                   *MSVCRT__errno() = MSVCRT_ENOSPC;
1541                   return s - buf_start;
1542                 }
1543             }
1544         }
1545       return s - buf_start;
1546     }
1547   return -1;
1548 }
1549
1550 /*********************************************************************
1551  *              _putw (MSVCRT.@)
1552  */
1553 int _putw(int val, MSVCRT_FILE* file)
1554 {
1555   return _write(file->_file, &val, sizeof(val)) == 1? val : MSVCRT_EOF;
1556 }
1557
1558 /*********************************************************************
1559  *              clearerr (MSVCRT.@)
1560  */
1561 void MSVCRT_clearerr(MSVCRT_FILE* file)
1562 {
1563   TRACE(":file (%p) fd (%d)\n",file,file->_file);
1564   file->_flag &= ~(MSVCRT__IOERR | MSVCRT__IOEOF);
1565 }
1566
1567 /*********************************************************************
1568  *              fclose (MSVCRT.@)
1569  */
1570 int MSVCRT_fclose(MSVCRT_FILE* file)
1571 {
1572   int r, flag;
1573
1574   flag = file->_flag;
1575   r=_close(file->_file);
1576   return ((r==MSVCRT_EOF) || (flag & MSVCRT__IOERR) ? MSVCRT_EOF : 0);
1577 }
1578
1579 /*********************************************************************
1580  *              feof (MSVCRT.@)
1581  */
1582 int MSVCRT_feof(MSVCRT_FILE* file)
1583 {
1584   return file->_flag & MSVCRT__IOEOF;
1585 }
1586
1587 /*********************************************************************
1588  *              ferror (MSVCRT.@)
1589  */
1590 int MSVCRT_ferror(MSVCRT_FILE* file)
1591 {
1592   return file->_flag & MSVCRT__IOERR;
1593 }
1594
1595 /*********************************************************************
1596  *              fflush (MSVCRT.@)
1597  */
1598 int MSVCRT_fflush(MSVCRT_FILE* file)
1599 {
1600   if(!file) {
1601         _flushall();
1602         return 0;
1603   } else {
1604         int res=msvcrt_flush_buffer(file);
1605         return res;
1606   }
1607 }
1608
1609 /*********************************************************************
1610  *              fgetc (MSVCRT.@)
1611  */
1612 int MSVCRT_fgetc(MSVCRT_FILE* file)
1613 {
1614   if (file->_cnt>0) {
1615         file->_cnt--;
1616         return *(unsigned char *)file->_ptr++;
1617   } else {
1618         return _filbuf(file);
1619   }
1620 }
1621
1622 /*********************************************************************
1623  *              _fgetchar (MSVCRT.@)
1624  */
1625 int _fgetchar(void)
1626 {
1627   return MSVCRT_fgetc(MSVCRT_stdin);
1628 }
1629
1630 /*********************************************************************
1631  *              _filbuf (MSVCRT.@)
1632  */
1633 int _filbuf(MSVCRT_FILE* file)
1634 {
1635
1636   /* Allocate buffer if needed */
1637   if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF) ) {
1638         msvcrt_alloc_buffer(file);
1639   }
1640   if(!(file->_flag & MSVCRT__IOREAD)) {
1641         if(file->_flag & MSVCRT__IORW) {
1642                 file->_flag |= MSVCRT__IOREAD;
1643         } else {
1644                 return MSVCRT_EOF;
1645         }
1646   }
1647   if(file->_flag & MSVCRT__IONBF) {
1648         unsigned char c;
1649         if (_read(file->_file,&c,1) != 1) {
1650                 file->_flag |= MSVCRT__IOEOF;
1651                 return MSVCRT_EOF;
1652         }
1653         return c;
1654   } else {
1655         file->_cnt = _read(file->_file, file->_base, file->_bufsiz);
1656         if(file->_cnt<0) file->_cnt = 0;
1657         if(!file->_cnt) {
1658                 file->_flag |= MSVCRT__IOEOF;
1659                 return MSVCRT_EOF;
1660         }
1661         file->_cnt--;
1662         file->_ptr = file->_base+1;
1663         return *(unsigned char *)file->_base;
1664   }
1665 }
1666
1667 /*********************************************************************
1668  *              fgetpos (MSVCRT.@)
1669  */
1670 int MSVCRT_fgetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
1671 {
1672   *pos = MSVCRT_ftell(file);
1673   return (*pos == -1? -1 : 0);
1674 }
1675
1676 /*********************************************************************
1677  *              fgets (MSVCRT.@)
1678  */
1679 char *MSVCRT_fgets(char *s, int size, MSVCRT_FILE* file)
1680 {
1681   int    cc;
1682   char * buf_start = s;
1683
1684   TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
1685         file,file->_file,s,size);
1686
1687   for(cc = MSVCRT_fgetc(file); cc != MSVCRT_EOF && cc != '\n';
1688       cc = MSVCRT_fgetc(file))
1689     /* _read already handled the translation */
1690     {
1691       if (--size <= 0) break;
1692       *s++ = (char)cc;
1693     }
1694   if ((cc == MSVCRT_EOF) && (s == buf_start)) /* If nothing read, return 0*/
1695   {
1696     TRACE(":nothing read\n");
1697     return 0;
1698   }
1699   if (cc == '\n')
1700     if (--size > 0)
1701       *s++ = '\n';
1702   *s = '\0';
1703   TRACE(":got '%s'\n", debugstr_a(buf_start));
1704   return buf_start;
1705 }
1706
1707 /*********************************************************************
1708  *              fgetwc (MSVCRT.@)
1709  *
1710  * In _O_TEXT mode, bultibyte characters are read from the file, dropping
1711  * the CR from CR/LF combinations
1712  */
1713 MSVCRT_wint_t MSVCRT_fgetwc(MSVCRT_FILE* file)
1714 {
1715   char c;
1716
1717   if (file->_flag & _O_BINARY)
1718     {
1719       MSVCRT_wchar_t wc;
1720       if (_read(file->_file, &wc, sizeof(wc)) != sizeof(wc))
1721         return MSVCRT_WEOF;
1722       return wc;
1723     }
1724   c = MSVCRT_fgetc(file);
1725   if ((*__p___mb_cur_max() > 1) && MSVCRT_isleadbyte(c))
1726     {
1727       FIXME("Treat Multibyte characters\n");
1728     }
1729   if (c == MSVCRT_EOF)
1730     return MSVCRT_WEOF;
1731   else
1732     return (MSVCRT_wint_t)c;
1733 }
1734
1735 /*********************************************************************
1736  *              getwc (MSVCRT.@)
1737  */
1738 MSVCRT_wint_t MSVCRT_getwc(MSVCRT_FILE* file)
1739 {
1740   return MSVCRT_fgetwc(file);
1741 }
1742
1743 /*********************************************************************
1744  *              _fgetwchar (MSVCRT.@)
1745  */
1746 MSVCRT_wint_t _fgetwchar(void)
1747 {
1748   return MSVCRT_fgetwc(MSVCRT_stdin);
1749 }
1750
1751 /*********************************************************************
1752  *              getwchar (MSVCRT.@)
1753  */
1754 MSVCRT_wint_t MSVCRT_getwchar(void)
1755 {
1756   return _fgetwchar();
1757 }
1758
1759 /*********************************************************************
1760  *              fgetws (MSVCRT.@)
1761  */
1762 MSVCRT_wchar_t *MSVCRT_fgetws(MSVCRT_wchar_t *s, int size, MSVCRT_FILE* file)
1763 {
1764   int    cc;
1765   MSVCRT_wchar_t * buf_start = s;
1766
1767   TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
1768         file,file->_file,s,size);
1769
1770   for(cc = MSVCRT_fgetwc(file); cc != MSVCRT_WEOF && cc != L'\n';
1771       cc = MSVCRT_fgetwc(file))
1772     /* _read already handled the translation */
1773     {
1774       if (--size <= 0) break;
1775       *s++ = cc;
1776     }
1777   if ((cc == MSVCRT_EOF) && (s == buf_start)) /* If nothing read, return 0*/
1778   {
1779     TRACE(":nothing read\n");
1780     return 0;
1781   }
1782   if (cc == L'\n')
1783     if (--size > 0)
1784       *s++ = '\n';
1785   *s = '\0';
1786 /*  TRACE(":got '%s'\n", buf_start); */
1787   return buf_start;
1788 }
1789
1790
1791 /*********************************************************************
1792  *              fputwc (MSVCRT.@)
1793  */
1794 MSVCRT_wint_t MSVCRT_fputwc(MSVCRT_wint_t wc, MSVCRT_FILE* file)
1795 {
1796   MSVCRT_wchar_t mwc=wc;
1797   if (MSVCRT_fwrite( &mwc, sizeof(mwc), 1, file) != 1)
1798     return MSVCRT_WEOF;
1799   return wc;
1800 }
1801
1802 /*********************************************************************
1803  *              _fputwchar (MSVCRT.@)
1804  */
1805 MSVCRT_wint_t _fputwchar(MSVCRT_wint_t wc)
1806 {
1807   return MSVCRT_fputwc(wc, MSVCRT_stdout);
1808 }
1809
1810 /*********************************************************************
1811  *              fopen (MSVCRT.@)
1812  */
1813 MSVCRT_FILE* MSVCRT_fopen(const char *path, const char *mode)
1814 {
1815   MSVCRT_FILE* file;
1816   int flags = 0, plus = 0, fd;
1817   const char* search = mode;
1818
1819   TRACE("(%s,%s)\n",path,mode);
1820
1821   while (*search)
1822     if (*search++ == '+')
1823       plus = 1;
1824
1825   /* map mode string to open() flags. "man fopen" for possibilities. */
1826   switch(*mode++)
1827   {
1828   case 'R': case 'r':
1829     flags = (plus ? _O_RDWR : _O_RDONLY);
1830     break;
1831   case 'W': case 'w':
1832     flags = _O_CREAT | _O_TRUNC | (plus  ? _O_RDWR : _O_WRONLY);
1833     break;
1834   case 'A': case 'a':
1835     flags = _O_CREAT | _O_APPEND | (plus  ? _O_RDWR : _O_WRONLY);
1836     break;
1837   default:
1838     return NULL;
1839   }
1840
1841   while (*mode)
1842     switch (*mode++)
1843     {
1844     case 'B': case 'b':
1845       flags |=  _O_BINARY;
1846       flags &= ~_O_TEXT;
1847       break;
1848     case 'T': case 't':
1849       flags |=  _O_TEXT;
1850       flags &= ~_O_BINARY;
1851       break;
1852     case '+':
1853       break;
1854     default:
1855       FIXME(":unknown flag %c not supported\n",mode[-1]);
1856     }
1857
1858   fd = _open(path, flags);
1859
1860   if (fd < 0)
1861     return NULL;
1862
1863   file = msvcrt_alloc_fp(fd);
1864   TRACE(":got (%p)\n",file);
1865   if (!file)
1866     _close(fd);
1867
1868   return file;
1869 }
1870
1871 /*********************************************************************
1872  *              _wfopen (MSVCRT.@)
1873  */
1874 MSVCRT_FILE *_wfopen(const MSVCRT_wchar_t *path, const MSVCRT_wchar_t *mode)
1875 {
1876   const unsigned int plen = strlenW(path), mlen = strlenW(mode);
1877   char *patha = MSVCRT_calloc(plen + 1, 1);
1878   char *modea = MSVCRT_calloc(mlen + 1, 1);
1879
1880   TRACE("(%s,%s)\n",debugstr_w(path),debugstr_w(mode));
1881
1882   if (patha && modea &&
1883       WideCharToMultiByte(CP_ACP,0,path,plen,patha,plen,NULL,NULL) &&
1884       WideCharToMultiByte(CP_ACP,0,mode,mlen,modea,mlen,NULL,NULL))
1885   {
1886     MSVCRT_FILE *retval = MSVCRT_fopen(patha,modea);
1887     MSVCRT_free(patha);
1888     MSVCRT_free(modea);
1889     return retval;
1890   }
1891
1892   MSVCRT__set_errno(GetLastError());
1893   return NULL;
1894 }
1895
1896 /*********************************************************************
1897  *              _fsopen (MSVCRT.@)
1898  */
1899 MSVCRT_FILE*  _fsopen(const char *path, const char *mode, int share)
1900 {
1901   FIXME(":(%s,%s,%d),ignoring share mode!\n",path,mode,share);
1902   return MSVCRT_fopen(path,mode);
1903 }
1904
1905 /*********************************************************************
1906  *              _wfsopen (MSVCRT.@)
1907  */
1908 MSVCRT_FILE*  _wfsopen(const MSVCRT_wchar_t *path, const MSVCRT_wchar_t *mode, int share)
1909 {
1910   FIXME(":(%s,%s,%d),ignoring share mode!\n",
1911         debugstr_w(path),debugstr_w(mode),share);
1912   return _wfopen(path,mode);
1913 }
1914
1915 /*********************************************************************
1916  *              fputc (MSVCRT.@)
1917  */
1918 int MSVCRT_fputc(int c, MSVCRT_FILE* file)
1919 {
1920   if(file->_cnt>0) {
1921         *file->_ptr++=c;
1922         file->_cnt--;
1923         return c;
1924   } else {
1925         return _flsbuf(c, file);
1926   }
1927 }
1928
1929 /*********************************************************************
1930  *              _flsbuf (MSVCRT.@)
1931  */
1932 int _flsbuf(int c, MSVCRT_FILE* file)
1933 {
1934   /* Flush output buffer */
1935   if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
1936         msvcrt_alloc_buffer(file);
1937   }
1938   if(!(file->_flag & MSVCRT__IOWRT)) {
1939         if(file->_flag & MSVCRT__IORW) {
1940                 file->_flag |= MSVCRT__IOWRT;
1941         } else {
1942                 return MSVCRT_EOF;
1943         }
1944   }
1945   if(file->_bufsiz) {
1946         int res=msvcrt_flush_buffer(file);
1947         return res?res : MSVCRT_fputc(c, file);
1948   } else {
1949         unsigned char cc=c;
1950         return _write(file->_file, &cc, 1) == 1? c : MSVCRT_EOF;
1951   }
1952 }
1953
1954 /*********************************************************************
1955  *              _fputchar (MSVCRT.@)
1956  */
1957 int _fputchar(int c)
1958 {
1959   return MSVCRT_fputc(c, MSVCRT_stdout);
1960 }
1961
1962 /*********************************************************************
1963  *              fread (MSVCRT.@)
1964  */
1965 MSVCRT_size_t MSVCRT_fread(void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
1966 { MSVCRT_size_t rcnt=size * nmemb;
1967   MSVCRT_size_t read=0;
1968   int pread=0;
1969   /* first buffered data */
1970   if(file->_cnt>0) {
1971         int pcnt= (rcnt>file->_cnt)? file->_cnt:rcnt;
1972         memcpy(ptr, file->_ptr, pcnt);
1973         file->_cnt -= pcnt;
1974         file->_ptr += pcnt;
1975         read += pcnt ;
1976         rcnt -= pcnt ;
1977        ptr = (char*)ptr + pcnt;
1978   } else if(!(file->_flag & MSVCRT__IOREAD )) {
1979         if(file->_flag & MSVCRT__IORW) {
1980                 file->_flag |= MSVCRT__IOREAD;
1981         } else
1982                 return 0;
1983   }
1984   if(rcnt) pread = _read(file->_file,ptr, rcnt);
1985   if (MSVCRT_flags[file->_file] & MSVCRT__IOEOF)
1986      /* expose feof condition in the flags
1987         MFC tests file->_flag for feof, and doesn't not call feof())
1988     */
1989     file->_flag |= MSVCRT__IOEOF;
1990   if (pread <= 0)
1991     pread = 0;
1992   read+=pread;
1993   return read / size;
1994 }
1995
1996 /*********************************************************************
1997  *              freopen (MSVCRT.@)
1998  *
1999  */
2000 MSVCRT_FILE* MSVCRT_freopen(const char *path, const char *mode,MSVCRT_FILE* file)
2001 {
2002   MSVCRT_FILE* newfile;
2003   int fd;
2004
2005   TRACE(":path (%p) mode (%s) file (%p) fd (%d)\n",path,mode,file,file->_file);
2006   if (!file || ((fd = file->_file) < 0) || fd > MSVCRT_fdend)
2007     return NULL;
2008
2009   if (fd > 2)
2010   {
2011 #if 0
2012     FIXME(":reopen on user file not implemented!\n");
2013     MSVCRT__set_errno(ERROR_CALL_NOT_IMPLEMENTED);
2014     return NULL;
2015 #endif
2016     if(MSVCRT_fclose(file))
2017         return NULL;
2018     return MSVCRT_fopen(path, mode);
2019   }
2020
2021   /* first, create the new file */
2022   if ((newfile = MSVCRT_fopen(path,mode)) == NULL)
2023     return NULL;
2024
2025   if (fd < 3 && SetStdHandle(fd == 0 ? STD_INPUT_HANDLE :
2026      (fd == 1? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE),
2027       MSVCRT_handles[newfile->_file]))
2028   {
2029     /* Redirecting std handle to file , copy over.. */
2030     MSVCRT_handles[fd] = MSVCRT_handles[newfile->_file];
2031     MSVCRT_flags[fd] = MSVCRT_flags[newfile->_file];
2032     memcpy(&MSVCRT__iob[fd], newfile, sizeof (MSVCRT_FILE));
2033     MSVCRT__iob[fd]._file = fd;
2034     /* And free up the resources allocated by fopen, but
2035      * not the HANDLE we copied. */
2036     MSVCRT_free(MSVCRT_files[fd]);
2037     msvcrt_free_fd(newfile->_file);
2038     return &MSVCRT__iob[fd];
2039   }
2040
2041   WARN(":failed-last error (%ld)\n",GetLastError());
2042   MSVCRT_fclose(newfile);
2043   MSVCRT__set_errno(GetLastError());
2044   return NULL;
2045 }
2046
2047 /*********************************************************************
2048  *              fsetpos (MSVCRT.@)
2049  */
2050 int MSVCRT_fsetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
2051 {
2052   return _lseek(file->_file,*pos,SEEK_SET);
2053 }
2054
2055 /*********************************************************************
2056  *              fseek (MSVCRT.@)
2057  */
2058 int MSVCRT_fseek(MSVCRT_FILE* file, long offset, int whence)
2059 {
2060   /* Flush output if needed */
2061   if(file->_flag & MSVCRT__IOWRT)
2062         msvcrt_flush_buffer(file);
2063
2064   if(whence == SEEK_CUR && file->_flag & MSVCRT__IOREAD ) {
2065         offset -= file->_cnt;
2066   }
2067   /* Discard buffered input */
2068   file->_cnt = 0;
2069   file->_ptr = file->_base;
2070   /* Reset direction of i/o */
2071   if(file->_flag & MSVCRT__IORW) {
2072         file->_flag &= ~(MSVCRT__IOREAD|MSVCRT__IOWRT);
2073   }
2074   return (_lseek(file->_file,offset,whence) == -1)?-1:0;
2075 }
2076
2077 /*********************************************************************
2078  *              ftell (MSVCRT.@)
2079  */
2080 LONG MSVCRT_ftell(MSVCRT_FILE* file)
2081 {
2082   int off=0;
2083   long pos;
2084   if(file->_bufsiz)  {
2085         if( file->_flag & MSVCRT__IOWRT ) {
2086                 off = file->_ptr - file->_base;
2087         } else {
2088                 off = -file->_cnt;
2089         }
2090   }
2091   pos = _tell(file->_file);
2092   if(pos == -1) return pos;
2093   return off + pos;
2094 }
2095
2096 /*********************************************************************
2097  *              fwrite (MSVCRT.@)
2098  */
2099 MSVCRT_size_t MSVCRT_fwrite(const void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
2100 {
2101   MSVCRT_size_t wrcnt=size * nmemb;
2102   int written = 0;
2103   if (size == 0)
2104       return 0;
2105   if(file->_cnt) {
2106         int pcnt=(file->_cnt>wrcnt)? wrcnt: file->_cnt;
2107         memcpy(file->_ptr, ptr, pcnt);
2108         file->_cnt -= pcnt;
2109         file->_ptr += pcnt;
2110         written = pcnt;
2111         wrcnt -= pcnt;
2112        ptr = (char*)ptr + pcnt;
2113   } else if(!(file->_flag & MSVCRT__IOWRT)) {
2114         if(file->_flag & MSVCRT__IORW) {
2115                 file->_flag |= MSVCRT__IOWRT;
2116         } else
2117                 return 0;
2118   }
2119   if(wrcnt) {
2120         /* Flush buffer */
2121         int res=msvcrt_flush_buffer(file);
2122         if(!res) {
2123                 int pwritten = _write(file->_file, ptr, wrcnt);
2124                 if (pwritten <= 0) pwritten=0;
2125                 written += pwritten;
2126         }
2127   }
2128   return written / size;
2129 }
2130
2131 /*********************************************************************
2132  *              fputs (MSVCRT.@)
2133  */
2134 int MSVCRT_fputs(const char *s, MSVCRT_FILE* file)
2135 {
2136     size_t i, len = strlen(s);
2137     if (file->_flag & _O_BINARY)
2138       return MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
2139     for (i=0; i<len; i++)
2140       if (MSVCRT_fputc(s[i], file) == MSVCRT_EOF) 
2141         return MSVCRT_EOF;
2142     return 0;
2143 }
2144
2145 /*********************************************************************
2146  *              fputws (MSVCRT.@)
2147  */
2148 int MSVCRT_fputws(const MSVCRT_wchar_t *s, MSVCRT_FILE* file)
2149 {
2150     size_t i, len = strlenW(s);
2151     if (file->_flag & _O_BINARY)
2152       return MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
2153     for (i=0; i<len; i++)
2154       {
2155         if ((s[i] == L'\n') && (MSVCRT_fputc('\r', file) == MSVCRT_EOF))
2156           return MSVCRT_WEOF;
2157         if (MSVCRT_fputwc(s[i], file) == MSVCRT_WEOF)
2158           return MSVCRT_WEOF; 
2159       }
2160     return 0;
2161 }
2162
2163 /*********************************************************************
2164  *              getchar (MSVCRT.@)
2165  */
2166 int MSVCRT_getchar(void)
2167 {
2168   return MSVCRT_fgetc(MSVCRT_stdin);
2169 }
2170
2171 /*********************************************************************
2172  *              getc (MSVCRT.@)
2173  */
2174 int MSVCRT_getc(MSVCRT_FILE* file)
2175 {
2176   return MSVCRT_fgetc(file);
2177 }
2178
2179 /*********************************************************************
2180  *              gets (MSVCRT.@)
2181  */
2182 char *MSVCRT_gets(char *buf)
2183 {
2184   int    cc;
2185   char * buf_start = buf;
2186
2187   for(cc = MSVCRT_fgetc(MSVCRT_stdin); cc != MSVCRT_EOF && cc != '\n';
2188       cc = MSVCRT_fgetc(MSVCRT_stdin))
2189   if(cc != '\r') *buf++ = (char)cc;
2190
2191   *buf = '\0';
2192
2193   TRACE("got '%s'\n", buf_start);
2194   return buf_start;
2195 }
2196
2197 /*********************************************************************
2198  *              _getws (MSVCRT.@)
2199  */
2200 MSVCRT_wchar_t* MSVCRT__getws(MSVCRT_wchar_t* buf)
2201 {
2202     MSVCRT_wint_t cc;
2203     MSVCRT_wchar_t* ws = buf;
2204
2205     for (cc = MSVCRT_fgetwc(MSVCRT_stdin); cc != MSVCRT_WEOF && cc != '\n';
2206          cc = MSVCRT_fgetwc(MSVCRT_stdin))
2207     {
2208         if (cc != '\r')
2209             *buf++ = (MSVCRT_wchar_t)cc;
2210     }
2211     *buf = '\0';
2212
2213     TRACE("got '%s'\n", debugstr_w(ws));
2214     return ws;
2215 }
2216
2217 /*********************************************************************
2218  *              putc (MSVCRT.@)
2219  */
2220 int MSVCRT_putc(int c, MSVCRT_FILE* file)
2221 {
2222   return MSVCRT_fputc(c, file);
2223 }
2224
2225 /*********************************************************************
2226  *              putchar (MSVCRT.@)
2227  */
2228 int MSVCRT_putchar(int c)
2229 {
2230   return MSVCRT_fputc(c, MSVCRT_stdout);
2231 }
2232
2233 /*********************************************************************
2234  *              puts (MSVCRT.@)
2235  */
2236 int MSVCRT_puts(const char *s)
2237 {
2238     size_t len = strlen(s);
2239     if (MSVCRT_fwrite(s,sizeof(*s),len,MSVCRT_stdout) != len) return MSVCRT_EOF;
2240     return MSVCRT_fwrite("\n",1,1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
2241 }
2242
2243 /*********************************************************************
2244  *              _putws (MSVCRT.@)
2245  */
2246 int _putws(const MSVCRT_wchar_t *s)
2247 {
2248     static const MSVCRT_wchar_t nl = '\n';
2249     size_t len = strlenW(s);
2250     if (MSVCRT_fwrite(s,sizeof(*s),len,MSVCRT_stdout) != len) return MSVCRT_EOF;
2251     return MSVCRT_fwrite(&nl,sizeof(nl),1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
2252 }
2253
2254 /*********************************************************************
2255  *              remove (MSVCRT.@)
2256  */
2257 int MSVCRT_remove(const char *path)
2258 {
2259   TRACE("(%s)\n",path);
2260   if (DeleteFileA(path))
2261     return 0;
2262   TRACE(":failed (%ld)\n",GetLastError());
2263   MSVCRT__set_errno(GetLastError());
2264   return -1;
2265 }
2266
2267 /*********************************************************************
2268  *              _wremove (MSVCRT.@)
2269  */
2270 int _wremove(const MSVCRT_wchar_t *path)
2271 {
2272   TRACE("(%s)\n",debugstr_w(path));
2273   if (DeleteFileW(path))
2274     return 0;
2275   TRACE(":failed (%ld)\n",GetLastError());
2276   MSVCRT__set_errno(GetLastError());
2277   return -1;
2278 }
2279
2280 /*********************************************************************
2281  *              scanf (MSVCRT.@)
2282  */
2283 int MSVCRT_scanf(const char *format, ...)
2284 {
2285   va_list valist;
2286   int res;
2287
2288   va_start(valist, format);
2289   res = MSVCRT_fscanf(MSVCRT_stdin, format, valist);
2290   va_end(valist);
2291   return res;
2292 }
2293
2294 /*********************************************************************
2295  *              wscanf (MSVCRT.@)
2296  */
2297 int MSVCRT_wscanf(const MSVCRT_wchar_t *format, ...)
2298 {
2299   va_list valist;
2300   int res;
2301
2302   va_start(valist, format);
2303   res = MSVCRT_fwscanf(MSVCRT_stdin, format, valist);
2304   va_end(valist);
2305   return res;
2306 }
2307
2308 /*********************************************************************
2309  *              rename (MSVCRT.@)
2310  */
2311 int MSVCRT_rename(const char *oldpath,const char *newpath)
2312 {
2313   TRACE(":from %s to %s\n",oldpath,newpath);
2314   if (MoveFileExA(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
2315     return 0;
2316   TRACE(":failed (%ld)\n",GetLastError());
2317   MSVCRT__set_errno(GetLastError());
2318   return -1;
2319 }
2320
2321 /*********************************************************************
2322  *              _wrename (MSVCRT.@)
2323  */
2324 int _wrename(const MSVCRT_wchar_t *oldpath,const MSVCRT_wchar_t *newpath)
2325 {
2326   TRACE(":from %s to %s\n",debugstr_w(oldpath),debugstr_w(newpath));
2327   if (MoveFileExW(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
2328     return 0;
2329   TRACE(":failed (%ld)\n",GetLastError());
2330   MSVCRT__set_errno(GetLastError());
2331   return -1;
2332 }
2333
2334 /*********************************************************************
2335  *              setvbuf (MSVCRT.@)
2336  */
2337 int MSVCRT_setvbuf(MSVCRT_FILE* file, char *buf, int mode, MSVCRT_size_t size)
2338 {
2339   /* TODO: Check if file busy */
2340   if(file->_bufsiz) {
2341         MSVCRT_free(file->_base);
2342         file->_bufsiz = 0;
2343         file->_cnt = 0;
2344   }
2345   if(mode == MSVCRT__IOFBF) {
2346         file->_flag &= ~MSVCRT__IONBF;
2347         file->_base = file->_ptr = buf;
2348         if(buf) {
2349                 file->_bufsiz = size;
2350         }
2351   } else {
2352         file->_flag |= MSVCRT__IONBF;
2353   }
2354   return 0;
2355 }
2356
2357 /*********************************************************************
2358  *              setbuf (MSVCRT.@)
2359  */
2360 void MSVCRT_setbuf(MSVCRT_FILE* file, char *buf)
2361 {
2362   MSVCRT_setvbuf(file, buf, buf ? MSVCRT__IOFBF : MSVCRT__IONBF, MSVCRT_BUFSIZ);
2363 }
2364
2365 /*********************************************************************
2366  *              tmpnam (MSVCRT.@)
2367  */
2368 char *MSVCRT_tmpnam(char *s)
2369 {
2370   char tmpbuf[MAX_PATH];
2371   char* prefix = "TMP";
2372   if (!GetTempPathA(MAX_PATH,tmpbuf) ||
2373       !GetTempFileNameA(tmpbuf,prefix,0,MSVCRT_tmpname))
2374   {
2375     TRACE(":failed-last error (%ld)\n",GetLastError());
2376     return NULL;
2377   }
2378   TRACE(":got tmpnam %s\n",MSVCRT_tmpname);
2379   s = MSVCRT_tmpname;
2380   return s;
2381 }
2382
2383 /*********************************************************************
2384  *              tmpfile (MSVCRT.@)
2385  */
2386 MSVCRT_FILE* MSVCRT_tmpfile(void)
2387 {
2388   char *filename = MSVCRT_tmpnam(NULL);
2389   int fd;
2390   fd = _open(filename, _O_CREAT | _O_BINARY | _O_RDWR | _O_TEMPORARY);
2391   if (fd != -1)
2392     return msvcrt_alloc_fp(fd);
2393   return NULL;
2394 }
2395
2396 /*********************************************************************
2397  *              vfprintf (MSVCRT.@)
2398  */
2399 int MSVCRT_vfprintf(MSVCRT_FILE* file, const char *format, va_list valist)
2400 {
2401   char buf[2048], *mem = buf;
2402   int written, resize = sizeof(buf), retval;
2403   /* There are two conventions for vsnprintf failing:
2404    * Return -1 if we truncated, or
2405    * Return the number of bytes that would have been written
2406    * The code below handles both cases
2407    */
2408   while ((written = vsnprintf(mem, resize, format, valist)) == -1 ||
2409           written > resize)
2410   {
2411     resize = (written == -1 ? resize * 2 : written + 1);
2412     if (mem != buf)
2413       MSVCRT_free (mem);
2414     if (!(mem = (char *)MSVCRT_malloc(resize)))
2415       return MSVCRT_EOF;
2416   }
2417   retval = MSVCRT_fwrite(mem, sizeof(*mem), written, file);
2418   if (mem != buf)
2419     MSVCRT_free (mem);
2420   return retval;
2421 }
2422
2423 /*********************************************************************
2424  *              vfwprintf (MSVCRT.@)
2425  * FIXME:
2426  * Is final char included in written (then resize is too big) or not
2427  * (then we must test for equality too)?
2428  */
2429 int MSVCRT_vfwprintf(MSVCRT_FILE* file, const MSVCRT_wchar_t *format, va_list valist)
2430 {
2431   MSVCRT_wchar_t buf[2048], *mem = buf;
2432   int written, resize = sizeof(buf) / sizeof(MSVCRT_wchar_t), retval;
2433   /* See vfprintf comments */
2434   while ((written = _vsnwprintf(mem, resize, format, valist)) == -1 ||
2435           written > resize)
2436   {
2437     resize = (written == -1 ? resize * 2 : written + sizeof(MSVCRT_wchar_t));
2438     if (mem != buf)
2439       MSVCRT_free (mem);
2440     if (!(mem = (MSVCRT_wchar_t *)MSVCRT_malloc(resize*sizeof(*mem))))
2441       return MSVCRT_EOF;
2442   }
2443   retval = MSVCRT_fwrite(mem, sizeof(*mem), written, file);
2444   if (mem != buf)
2445     MSVCRT_free (mem);
2446   return retval;
2447 }
2448
2449 /*********************************************************************
2450  *              vprintf (MSVCRT.@)
2451  */
2452 int MSVCRT_vprintf(const char *format, va_list valist)
2453 {
2454   return MSVCRT_vfprintf(MSVCRT_stdout,format,valist);
2455 }
2456
2457 /*********************************************************************
2458  *              vwprintf (MSVCRT.@)
2459  */
2460 int MSVCRT_vwprintf(const MSVCRT_wchar_t *format, va_list valist)
2461 {
2462   return MSVCRT_vfwprintf(MSVCRT_stdout,format,valist);
2463 }
2464
2465 /*********************************************************************
2466  *              fprintf (MSVCRT.@)
2467  */
2468 int MSVCRT_fprintf(MSVCRT_FILE* file, const char *format, ...)
2469 {
2470     va_list valist;
2471     int res;
2472     va_start(valist, format);
2473     res = MSVCRT_vfprintf(file, format, valist);
2474     va_end(valist);
2475     return res;
2476 }
2477
2478 /*********************************************************************
2479  *              fwprintf (MSVCRT.@)
2480  */
2481 int MSVCRT_fwprintf(MSVCRT_FILE* file, const MSVCRT_wchar_t *format, ...)
2482 {
2483     va_list valist;
2484     int res;
2485     va_start(valist, format);
2486     res = MSVCRT_vfwprintf(file, format, valist);
2487     va_end(valist);
2488     return res;
2489 }
2490
2491 /*********************************************************************
2492  *              printf (MSVCRT.@)
2493  */
2494 int MSVCRT_printf(const char *format, ...)
2495 {
2496     va_list valist;
2497     int res;
2498     va_start(valist, format);
2499     res = MSVCRT_vfprintf(MSVCRT_stdout, format, valist);
2500     va_end(valist);
2501     return res;
2502 }
2503
2504 /*********************************************************************
2505  *              ungetc (MSVCRT.@)
2506  */
2507 int MSVCRT_ungetc(int c, MSVCRT_FILE * file)
2508 {
2509         if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
2510                 msvcrt_alloc_buffer(file);
2511                 file->_ptr++;
2512         }
2513         if(file->_ptr>file->_base) {
2514                 file->_ptr--;
2515                 *file->_ptr=c;
2516                 file->_cnt++;
2517                 return c;
2518         }
2519         return MSVCRT_EOF;
2520 }
2521
2522 /*********************************************************************
2523  *              ungetwc (MSVCRT.@)
2524  */
2525 MSVCRT_wint_t MSVCRT_ungetwc(MSVCRT_wint_t wc, MSVCRT_FILE * file)
2526 {
2527         MSVCRT_wchar_t mwc = wc;
2528         char * pp = (char *)&mwc;
2529         int i;
2530         for(i=sizeof(MSVCRT_wchar_t)-1;i>=0;i--) {
2531                 if(pp[i] != MSVCRT_ungetc(pp[i],file))
2532                         return MSVCRT_WEOF;
2533         }
2534         return mwc;
2535 }
2536
2537 /*********************************************************************
2538  *              wprintf (MSVCRT.@)
2539  */
2540 int MSVCRT_wprintf(const MSVCRT_wchar_t *format, ...)
2541 {
2542     va_list valist;
2543     int res;
2544     va_start(valist, format);
2545     res = MSVCRT_vwprintf(format, valist);
2546     va_end(valist);
2547     return res;
2548 }