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