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