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