Added a first-cut version of MapVirtualKeyExW() that has the same
[wine] / dlls / crtdll / file.c
1 /*
2  * CRTDLL 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  * Implementation Notes:
10  * Mapping is performed between FILE*, fd and HANDLE's. This allows us to 
11  * implement all calls using the Win32 API, support remapping fd's to 
12  * FILES and do some other tricks as well (like closeall, _get_osfhandle).
13  * For mix and matching with the host libc, processes can use the Win32 HANDLE
14  * to get a real unix fd from the wineserver. Or we could do this once
15  * on create, and provide a function to return it quickly (store it
16  * in the mapping table). Note that If you actuall _do_ this, you should
17  * call rewind() before using any other crt functions on the file. To avoid
18  * the confusion I got when reading the API docs, fd is always refered
19  * to as a file descriptor here. In the API docs its called a file handle
20  * which is confusing with Win32 HANDLES.
21  * M$ CRT includes inline versions of some of these functions (like feof()).
22  * These inlines check/modify bitfields in the FILE structure, so we set
23  * _flags/_file/_cnt in the FILE* to be binary compatible with the win dll.
24  * lcc defines _IOAPPEND as one of the flags for a FILE*, but testing shows
25  * that M$ CRT never sets it. So we keep the flag in our mapping table but
26  * mask it out when we populate a FILE* with it. Then when we write we seek
27  * to EOF if _IOAPPEND is set for the underlying fd.
28  *
29  * FIXME:
30  * Not MT safe. Need locking around file access and allocation for this.
31  * NT has no effective limit on files - neither should we. This will be fixed
32  * with dynamic allocation of the file mapping array.
33  * Buffering is handled differently. Have to investigate a) how much control
34  * we have over buffering in win32, and b) if we care ;-)
35  */
36
37 #include "crtdll.h"
38 #include <stdarg.h>
39 #include <string.h>
40 #include <ctype.h>
41 #include <errno.h>
42 #include "ntddk.h"
43
44 DEFAULT_DEBUG_CHANNEL(crtdll);
45
46 /* FIXME: Make this dynamic */
47 #define CRTDLL_MAX_FILES 257
48
49 HANDLE __CRTDLL_handles[CRTDLL_MAX_FILES];
50 CRTDLL_FILE* __CRTDLL_files[CRTDLL_MAX_FILES];
51 INT  __CRTDLL_flags[CRTDLL_MAX_FILES];
52 CRTDLL_FILE __CRTDLL_iob[3];
53
54 static int __CRTDLL_fdstart = 3; /* first unallocated fd */
55 static int __CRTDLL_fdend = 3; /* highest allocated fd */
56
57 /* INTERNAL: process umask */
58 static INT __CRTDLL_umask = 0;
59
60 /* INTERNAL: Static buffer for temp file name */
61 static char CRTDLL_tmpname[MAX_PATH];
62
63 /* file extentions recognised as executables */
64 static const unsigned int EXE = 'e' << 16 | 'x' << 8 | 'e';
65 static const unsigned int BAT = 'b' << 16 | 'a' << 8 | 't';
66 static const unsigned int CMD = 'c' << 16 | 'm' << 8 | 'd';
67 static const unsigned int COM = 'c' << 16 | 'o' << 8 | 'm';
68
69 /* for stat mode, permissions apply to all,owner and group */
70 #define CRTDLL_S_IREAD  (_S_IREAD  | (_S_IREAD  >> 3) | (_S_IREAD  >> 6))
71 #define CRTDLL_S_IWRITE (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6))
72 #define CRTDLL_S_IEXEC  (_S_IEXEC  | (_S_IEXEC  >> 3) | (_S_IEXEC  >> 6))
73
74
75 /* INTERNAL: Get the HANDLE for a fd */
76 static HANDLE __CRTDLL__fdtoh(INT fd);
77 static HANDLE __CRTDLL__fdtoh(INT fd)
78 {
79   if (fd < 0 || fd >= __CRTDLL_fdend ||
80       __CRTDLL_handles[fd] == INVALID_HANDLE_VALUE)
81   {
82     WARN(":fd (%d) - no handle!\n",fd);
83     CRTDLL_doserrno = 0;
84     CRTDLL_errno = EBADF;
85    return INVALID_HANDLE_VALUE;
86   }
87   return __CRTDLL_handles[fd];
88 }
89
90
91 /* INTERNAL: free a file entry fd */
92 static void __CRTDLL__free_fd(INT fd);
93 static void __CRTDLL__free_fd(INT fd)
94 {
95   __CRTDLL_handles[fd] = INVALID_HANDLE_VALUE;
96   __CRTDLL_files[fd] = 0;
97   __CRTDLL_flags[fd] = 0;
98   TRACE(":fd (%d) freed\n",fd);
99   if (fd < 3)
100     return; /* dont use 0,1,2 for user files */
101   if (fd == __CRTDLL_fdend - 1)
102     __CRTDLL_fdend--;
103   if (fd < __CRTDLL_fdstart)
104     __CRTDLL_fdstart = fd;
105 }
106
107
108 /* INTERNAL: Allocate an fd slot from a Win32 HANDLE */
109 static INT __CRTDLL__alloc_fd(HANDLE hand, INT flag);
110 static INT __CRTDLL__alloc_fd(HANDLE hand, INT flag)
111 {
112   INT fd = __CRTDLL_fdstart;
113
114   TRACE(":handle (%d) allocating fd (%d)\n",hand,fd);
115   if (fd >= CRTDLL_MAX_FILES)
116   {
117     WARN(":files exhausted!\n");
118     return -1;
119   }
120   __CRTDLL_handles[fd] = hand;
121   __CRTDLL_flags[fd] = flag;
122
123   /* locate next free slot */
124   if (fd == __CRTDLL_fdend)
125     __CRTDLL_fdstart = ++__CRTDLL_fdend;
126   else
127     while(__CRTDLL_fdstart < __CRTDLL_fdend &&
128           __CRTDLL_handles[__CRTDLL_fdstart] != INVALID_HANDLE_VALUE)
129       __CRTDLL_fdstart++;
130
131   return fd;
132 }
133
134
135 /* INTERNAL: Allocate a FILE* for an fd slot
136  * This is done lazily to avoid memory wastage for low level open/write
137  * usage when a FILE* is not requested (but may be later).
138  */
139 static CRTDLL_FILE* __CRTDLL__alloc_fp(INT fd);
140 static CRTDLL_FILE* __CRTDLL__alloc_fp(INT fd)
141 {
142   TRACE(":fd (%d) allocating FILE*\n",fd);
143   if (fd < 0 || fd >= __CRTDLL_fdend || 
144       __CRTDLL_handles[fd] == INVALID_HANDLE_VALUE)
145   {
146     WARN(":invalid fd %d\n",fd);
147     CRTDLL_doserrno = 0;
148     CRTDLL_errno = EBADF;
149     return NULL;
150   }
151   if (!__CRTDLL_files[fd])
152   {
153     if ((__CRTDLL_files[fd] = CRTDLL_calloc(sizeof(CRTDLL_FILE),1)))
154     {
155       __CRTDLL_files[fd]->_file = fd;
156       __CRTDLL_files[fd]->_flag = __CRTDLL_flags[fd];
157       __CRTDLL_files[fd]->_flag &= ~_IOAPPEND; /* mask out, see above */
158     }
159   }
160   TRACE(":got FILE* (%p)\n",__CRTDLL_files[fd]);
161   return __CRTDLL_files[fd];
162 }
163
164
165 /* INTERNAL: Set up stdin, stderr and stdout */
166 VOID __CRTDLL__init_io(VOID)
167 {
168   int i;
169   memset(__CRTDLL_iob,0,3*sizeof(CRTDLL_FILE));
170   __CRTDLL_handles[0] = GetStdHandle(STD_INPUT_HANDLE);
171   __CRTDLL_flags[0] = __CRTDLL_iob[0]._flag = _IOREAD;
172   __CRTDLL_handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
173   __CRTDLL_flags[1] = __CRTDLL_iob[1]._flag = _IOWRT;
174   __CRTDLL_handles[2] = GetStdHandle(STD_ERROR_HANDLE);
175   __CRTDLL_flags[2] = __CRTDLL_iob[2]._flag = _IOWRT;
176
177   TRACE(":handles (%d)(%d)(%d)\n",__CRTDLL_handles[0],
178         __CRTDLL_handles[1],__CRTDLL_handles[2]);
179
180   for (i = 0; i < 3; i++)
181   {
182     /* FILE structs for stdin/out/err are static and never deleted */
183     __CRTDLL_files[i] = &__CRTDLL_iob[i];
184     __CRTDLL_iob[i]._file = i;
185   }
186 }
187
188
189 /*********************************************************************
190  *                  _access          (CRTDLL.37)
191  */
192 INT __cdecl CRTDLL__access(LPCSTR filename, INT mode)
193 {
194   DWORD attr = GetFileAttributesA(filename);
195
196   if (attr == 0xffffffff)
197   {
198     if (!filename)
199     {
200         /* FIXME: Should GetFileAttributesA() return this? */
201       __CRTDLL__set_errno(ERROR_INVALID_DATA);
202       return -1;
203     }
204     __CRTDLL__set_errno(GetLastError());
205     return -1;
206   }
207   if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & W_OK))
208   {
209     __CRTDLL__set_errno(ERROR_ACCESS_DENIED);
210     return -1;
211   }
212   TRACE(":file %s, mode (%d) ok\n",filename,mode);
213   return 0;
214 }
215
216
217 /*********************************************************************
218  *                  _chmod           (CRTDLL.054)
219  *
220  * Change a files permissions.
221  */
222 INT __cdecl CRTDLL__chmod(LPCSTR path, INT flags)
223 {
224   DWORD oldFlags = GetFileAttributesA(path);
225  
226   if (oldFlags != 0x0FFFFFFFF)
227   {
228     DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
229       oldFlags | FILE_ATTRIBUTE_READONLY;
230
231     if (newFlags == oldFlags || SetFileAttributesA( path, newFlags ))
232       return 0;
233   }
234   __CRTDLL__set_errno(GetLastError());
235   return -1;
236 }
237
238
239 /*********************************************************************
240  *                  _close           (CRTDLL.57)
241  *
242  * Close an open file descriptor.
243  */
244 INT __cdecl CRTDLL__close(INT fd)
245 {
246   HANDLE hand = __CRTDLL__fdtoh(fd);
247
248   TRACE(":fd (%d) handle (%d)\n",fd,hand);
249   if (hand == INVALID_HANDLE_VALUE)
250     return -1;
251
252   /* Dont free std FILE*'s, they are not dynamic */
253   if (fd > 2 && __CRTDLL_files[fd])
254     CRTDLL_free(__CRTDLL_files[fd]);
255
256   __CRTDLL__free_fd(fd);
257
258   if (!CloseHandle(hand))
259   {
260     WARN(":failed-last error (%ld)\n",GetLastError());
261     __CRTDLL__set_errno(GetLastError());
262     return -1;
263   }
264   TRACE(":ok\n");
265   return 0;
266 }
267
268
269 /*********************************************************************
270  *                  _commit           (CRTDLL.58)
271  *
272  * Ensure all file operations have been flushed to the drive.
273  */
274 INT __cdecl CRTDLL__commit(INT fd)
275 {
276   HANDLE hand = __CRTDLL__fdtoh(fd);
277
278   TRACE(":fd (%d) handle (%d)\n",fd,hand);
279   if (hand == INVALID_HANDLE_VALUE)
280     return -1;
281
282   if (!FlushFileBuffers(hand))
283   {
284     if (GetLastError() == ERROR_INVALID_HANDLE)
285     {
286       /* FlushFileBuffers fails for console handles
287        * so we ignore this error.
288        */
289       return 0;
290     }
291     TRACE(":failed-last error (%ld)\n",GetLastError());
292     __CRTDLL__set_errno(GetLastError());
293     return -1;
294   }
295   TRACE(":ok\n");
296   return 0;
297 }
298
299
300 /*********************************************************************
301  *                  _creat         (CRTDLL.066)
302  *
303  * Open a file, creating it if it is not present.
304  */
305 INT __cdecl CRTDLL__creat(LPCSTR path, INT flags)
306 {
307   INT usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
308   return CRTDLL__open(path, usedFlags);
309 }
310
311
312 /*********************************************************************
313  *                  _eof           (CRTDLL.076)
314  *
315  * Determine if the file pointer is at the end of a file.
316  *
317  * FIXME
318  *      Care for large files
319  */
320 INT __cdecl CRTDLL__eof( INT fd )
321 {
322   DWORD curpos,endpos;
323   HANDLE hand = __CRTDLL__fdtoh(fd);
324
325   TRACE(":fd (%d) handle (%d)\n",fd,hand);
326
327   if (hand == INVALID_HANDLE_VALUE)
328     return -1;
329
330   /* If we have a FILE* for this file, the EOF flag
331    * will be set by the read()/write() functions.
332    */
333   if (__CRTDLL_files[fd])
334     return __CRTDLL_files[fd]->_flag & _IOEOF;
335
336   /* Otherwise we do it the hard way */
337   curpos = SetFilePointer( hand, 0, NULL, SEEK_CUR );
338   endpos = SetFilePointer( hand, 0, NULL, FILE_END );
339
340   if (curpos == endpos)
341     return TRUE;
342
343   SetFilePointer( hand, curpos, 0, FILE_BEGIN);
344   return FALSE;
345 }
346
347
348 /*********************************************************************
349  *                  _fcloseall     (CRTDLL.089)
350  *
351  * Close all open files except stdin/stdout/stderr.
352  */
353 INT __cdecl CRTDLL__fcloseall(VOID)
354 {
355   int num_closed = 0, i = 3;
356
357   while(i < __CRTDLL_fdend)
358     if (__CRTDLL_handles[i] != INVALID_HANDLE_VALUE)
359     {
360       CRTDLL__close(i);
361       num_closed++;
362     }
363
364   TRACE(":closed (%d) handles\n",num_closed);
365   return num_closed;
366 }
367
368
369 /*********************************************************************
370  *                  _fdopen     (CRTDLL.091)
371  *
372  * Get a FILE* from a low level file descriptor.
373  */
374 CRTDLL_FILE* __cdecl CRTDLL__fdopen(INT fd, LPCSTR mode)
375 {
376   CRTDLL_FILE* file = __CRTDLL__alloc_fp(fd);
377
378   TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,mode,file);
379   if (file)
380     CRTDLL_rewind(file);
381
382   return file;
383 }
384
385
386 /*********************************************************************
387  *                  _fgetchar       (CRTDLL.092)
388  */
389 INT __cdecl CRTDLL__fgetchar( VOID )
390 {
391   return CRTDLL_fgetc(CRTDLL_stdin);
392 }
393
394
395 /*********************************************************************
396  *                  _filbuf     (CRTDLL.094)
397  *
398  * NOTES
399  * The macro version of getc calls this function whenever FILE->_cnt
400  * becomes negative. We ensure that _cnt is always 0 after any read
401  * so this function is always called. Our implementation simply calls
402  * fgetc as all the underlying buffering is handled by Wines 
403  * implementation of the Win32 file I/O calls.
404  */
405 INT __cdecl CRTDLL__filbuf(CRTDLL_FILE* file)
406 {
407   return CRTDLL_fgetc(file);
408 }
409
410 /*********************************************************************
411  *                   _filelength    (CRTDLL.097)
412  *
413  * Get the length of an open file.
414  */
415 LONG __cdecl CRTDLL__filelength(INT fd)
416 {
417   LONG curPos = CRTDLL__lseek(fd, 0, SEEK_CUR);
418   if (curPos != -1)
419   {
420     LONG endPos = CRTDLL__lseek(fd, 0, SEEK_END);
421     if (endPos != -1)
422     {
423       if (endPos != curPos)
424         CRTDLL__lseek(fd, curPos, SEEK_SET);
425       return endPos;
426     }
427   }
428   return -1;
429 }
430
431
432 /*********************************************************************
433  *                  _fileno     (CRTDLL.097)
434  *
435  * Get the file descriptor from a FILE*.
436  *
437  * NOTES
438  * This returns the CRTDLL fd, _not_ the underlying *nix fd.
439  */
440 INT __cdecl CRTDLL__fileno(CRTDLL_FILE* file)
441 {
442   TRACE(":FILE* (%p) fd (%d)\n",file,file->_file);
443   return file->_file;
444 }
445
446
447 /*********************************************************************
448  *                  _flsbuf     (CRTDLL.102)
449  *
450  * NOTES
451  * The macro version of putc calls this function whenever FILE->_cnt
452  * becomes negative. We ensure that _cnt is always 0 after any write
453  * so this function is always called. Our implementation simply calls
454  * fputc as all the underlying buffering is handled by Wines
455  * implementation of the Win32 file I/O calls.
456  */
457 INT __cdecl CRTDLL__flsbuf(INT c, CRTDLL_FILE* file)
458 {
459   return CRTDLL_fputc(c,file);
460 }
461
462
463 /*********************************************************************
464  *                  _flushall     (CRTDLL.103)
465  *
466  * Flush all open files.
467  */
468 INT __cdecl CRTDLL__flushall(VOID)
469 {
470   int num_flushed = 0, i = 3;
471
472   while(i < __CRTDLL_fdend)
473     if (__CRTDLL_handles[i] != INVALID_HANDLE_VALUE)
474     {
475       if (CRTDLL__commit(i) == -1)
476         if (__CRTDLL_files[i])
477           __CRTDLL_files[i]->_flag |= _IOERR;
478       num_flushed++;
479     }
480
481   TRACE(":flushed (%d) handles\n",num_flushed);
482   return num_flushed;
483 }
484
485
486 /*********************************************************************
487  *                  _fputchar     (CRTDLL.108)
488  *
489  * Put a character to a file.
490  */
491 INT __cdecl CRTDLL__fputchar(INT c)
492 {
493   return CRTDLL_fputc(c, CRTDLL_stdout);
494 }
495
496
497 /*********************************************************************
498  *                  _fsopen     (CRTDLL.110)
499  *
500  * Open a FILE* with sharing.
501  */
502 CRTDLL_FILE*  __cdecl CRTDLL__fsopen(LPCSTR path, LPCSTR mode, INT share)
503 {
504   FIXME(":(%s,%s,%d),ignoring share mode!\n",path,mode,share);
505   return CRTDLL_fopen(path,mode);
506 }
507
508
509 /*********************************************************************
510  *                  _fstat        (CRTDLL.111)
511  * 
512  * Get information about an open file.
513  */
514 int __cdecl CRTDLL__fstat(int fd, struct _stat* buf)
515 {
516   DWORD dw;
517   BY_HANDLE_FILE_INFORMATION hfi;
518   HANDLE hand = __CRTDLL__fdtoh(fd);
519
520   TRACE(":fd (%d) stat (%p)\n",fd,buf);
521   if (hand == INVALID_HANDLE_VALUE)
522     return -1;
523
524   if (!buf)
525   {
526     WARN(":failed-NULL buf\n");
527     __CRTDLL__set_errno(ERROR_INVALID_PARAMETER);
528     return -1;
529   }
530
531   memset(&hfi, 0, sizeof(hfi));
532   memset(buf, 0, sizeof(struct _stat));
533   if (!GetFileInformationByHandle(hand, &hfi))
534   {
535     WARN(":failed-last error (%ld)\n",GetLastError());
536     __CRTDLL__set_errno(ERROR_INVALID_PARAMETER);
537     return -1;
538   }
539   FIXME(":dwFileAttributes = %d, mode set to 0",hfi.dwFileAttributes);
540   buf->st_nlink = hfi.nNumberOfLinks;
541   buf->st_size  = hfi.nFileSizeLow;
542   RtlTimeToSecondsSince1970( &hfi.ftLastAccessTime, &dw );
543   buf->st_atime = dw;
544   RtlTimeToSecondsSince1970( &hfi.ftLastWriteTime, &dw );
545   buf->st_mtime = buf->st_ctime = dw;
546   return 0;
547 }
548
549
550 /*********************************************************************
551  *                  _futime        (CRTDLL.115)
552  * 
553  * Set the file access/modification times on an open file.
554  */
555 INT __cdecl CRTDLL__futime(INT fd, struct _utimbuf *t)
556 {
557   HANDLE hand = __CRTDLL__fdtoh(fd);
558   FILETIME at, wt;
559
560   if (!t)
561   {
562     time_t currTime;
563     CRTDLL_time(&currTime);
564     RtlSecondsSince1970ToTime( currTime, &at );
565     memcpy( &wt, &at, sizeof(wt) );
566   }
567   else
568   {
569     RtlSecondsSince1970ToTime( t->actime, &at );
570     if (t->actime == t->modtime)
571       memcpy( &wt, &at, sizeof(wt) );
572     else
573       RtlSecondsSince1970ToTime( t->modtime, &wt );
574   }
575
576   if (!SetFileTime( hand, NULL, &at, &wt ))
577   {
578     __CRTDLL__set_errno(GetLastError());
579     return -1 ;
580   }
581   return 0;
582 }
583
584
585 /*********************************************************************
586  *                  _get_osfhandle     (CRTDLL.117)
587  *
588  * Return a Win32 HANDLE from a file descriptor.
589  *
590  * PARAMS
591  * fd [in] A valid file descriptor
592  *
593  * RETURNS
594  * Success: A Win32 HANDLE
595  *
596  * Failure: INVALID_HANDLE_VALUE.
597  *
598  */
599 HANDLE CRTDLL__get_osfhandle(INT fd)
600 {
601   HANDLE hand = __CRTDLL__fdtoh(fd);
602   HANDLE newhand = hand;
603   TRACE(":fd (%d) handle (%d)\n",fd,hand);
604
605   if (hand != INVALID_HANDLE_VALUE)
606   {
607     /* FIXME: I'm not convinced that I should be copying the
608      * handle here - it may be leaked if the app doesn't 
609      * close it (and the API docs dont say that it should)
610      * Not duplicating it means that it can't be inherited
611      * and so lcc's wedit doesn't cope when it passes it to
612      * child processes. I've an idea that it should either
613      * be copied by CreateProcess, or marked as inheritable
614      * when initialised, or maybe both? JG 21-9-00.
615      */
616     DuplicateHandle(GetCurrentProcess(),hand,GetCurrentProcess(),
617                     &newhand,0,TRUE,DUPLICATE_SAME_ACCESS );
618   }
619   return newhand;
620 }
621
622
623 /*********************************************************************
624  *                  _getw       (CRTDLL.128)
625  *
626  * Read an integter from a FILE*.
627  */
628 INT __cdecl CRTDLL__getw( CRTDLL_FILE* file )
629 {
630   INT i;
631   if (CRTDLL__read(file->_file, &i, sizeof(INT)) != 1)
632     return EOF;
633   return i;
634 }
635
636
637 /*********************************************************************
638  *                  _isatty       (CRTDLL.137)
639  *
640  * Return non zero if fd is a character device (e.g console).
641  */
642 INT __cdecl CRTDLL__isatty(INT fd)
643 {
644   HANDLE hand = __CRTDLL__fdtoh(fd);
645
646   TRACE(":fd (%d) handle (%d)\n",fd,hand);
647   if (hand == INVALID_HANDLE_VALUE)
648     return 0;
649
650   return GetFileType(fd) == FILE_TYPE_CHAR? 1 : 0;
651 }
652
653
654 /*********************************************************************
655  *                  _lseek     (CRTDLL.179)
656  *
657  * Move the file pointer within a file.
658  */
659 LONG __cdecl CRTDLL__lseek( INT fd, LONG offset, INT whence)
660 {
661   DWORD ret;
662   HANDLE hand = __CRTDLL__fdtoh(fd);
663
664   TRACE(":fd (%d) handle (%d)\n",fd,hand);
665   if (hand == INVALID_HANDLE_VALUE)
666     return -1;
667
668   if (whence < 0 || whence > 2)
669   {
670     CRTDLL_errno = EINVAL;
671     return -1;
672   }
673
674   TRACE(":fd (%d) to 0x%08lx pos %s\n",
675         fd,offset,(whence==SEEK_SET)?"SEEK_SET":
676         (whence==SEEK_CUR)?"SEEK_CUR":
677         (whence==SEEK_END)?"SEEK_END":"UNKNOWN");
678
679   if ((ret = SetFilePointer( hand, offset, NULL, whence )) != 0xffffffff)
680   {
681     if ( __CRTDLL_files[fd])
682       __CRTDLL_files[fd]->_flag &= ~_IOEOF;
683     /* FIXME: What if we seek _to_ EOF - is EOF set? */
684     return ret;
685   }
686   TRACE(":error-last error (%ld)\n",GetLastError());
687   if ( __CRTDLL_files[fd])
688     switch(GetLastError())
689     {
690     case ERROR_NEGATIVE_SEEK:
691     case ERROR_SEEK_ON_DEVICE:
692       __CRTDLL__set_errno(GetLastError());
693       __CRTDLL_files[fd]->_flag |= _IOERR;
694       break;
695     default:
696       break;
697     }
698   return -1;
699 }
700
701 /*********************************************************************
702  *                  _mktemp           (CRTDLL.239)
703  *
704  * Create a temporary file name.
705  */
706 LPSTR __cdecl CRTDLL__mktemp(LPSTR pattern)
707 {
708   int numX = 0;
709   LPSTR retVal = pattern;
710   INT id;
711   char letter = 'a';
712
713   while(*pattern)
714     numX = (*pattern++ == 'X')? numX + 1 : 0;
715   if (numX < 5)
716     return NULL;
717   pattern--;
718   id = GetCurrentProcessId();
719   numX = 6;
720   while(numX--)
721   {
722     INT tempNum = id / 10;
723     *pattern-- = id - (tempNum * 10) + '0';
724     id = tempNum;
725   }
726   pattern++;
727   do
728   {
729     if (GetFileAttributesA( retVal ) == 0xFFFFFFFF &&
730         GetLastError() == ERROR_FILE_NOT_FOUND)
731       return retVal;
732     *pattern = letter++;
733   } while(letter != '|');
734   return NULL;
735 }
736
737 /*********************************************************************
738  *                  _open           (CRTDLL.239)
739  * Open a file.
740  */
741 INT __cdecl CRTDLL__open(LPCSTR path,INT flags)
742 {
743   DWORD access = 0, creation = 0;
744   INT ioflag = 0, fd;
745   HANDLE hand;
746
747   TRACE(":file (%s) mode 0x%04x\n",path,flags);
748
749   switch(flags & (_O_RDONLY | _O_WRONLY | _O_RDWR))
750   {
751   case _O_RDONLY:
752     access |= GENERIC_READ;
753     ioflag |= _IOREAD;
754     break;
755   case _O_WRONLY:
756     access |= GENERIC_WRITE;
757     ioflag |= _IOWRT;
758     break;
759   case _O_RDWR:
760     access |= GENERIC_WRITE | GENERIC_READ;
761     ioflag |= _IORW;
762     break;
763   }
764
765   if (flags & _O_CREAT)
766   {
767     if (flags & _O_EXCL)
768       creation = CREATE_NEW;
769     else if (flags & _O_TRUNC)
770       creation = CREATE_ALWAYS;
771     else
772       creation = OPEN_ALWAYS;
773   }
774   else  /* no _O_CREAT */
775   {
776     if (flags & _O_TRUNC)
777       creation = TRUNCATE_EXISTING;
778     else
779       creation = OPEN_EXISTING;
780   }
781   if (flags & _O_APPEND)
782     ioflag |= _IOAPPEND;
783
784
785   flags |= _O_BINARY; /* FIXME: Default to text */
786
787   if (flags & _O_TEXT)
788   {
789     /* Dont warn when writing */
790     if (ioflag & GENERIC_READ)
791       FIXME(":TEXT node not implemented\n");
792     flags &= ~_O_TEXT;
793   }
794
795   if (flags & ~(_O_BINARY|_O_TEXT|_O_APPEND|_O_TRUNC|_O_EXCL|_O_CREAT|_O_RDWR))
796     TRACE(":unsupported flags 0x%04x\n",flags);
797
798   /* clear those pesky flags ;-) */
799   flags &= (_O_BINARY|_O_TEXT|_O_APPEND|_O_TRUNC|_O_EXCL|_O_CREAT|_O_RDWR);
800
801   hand = CreateFileA( path, access, FILE_SHARE_READ | FILE_SHARE_WRITE,
802                       NULL, creation, FILE_ATTRIBUTE_NORMAL, -1);
803
804   if (hand == INVALID_HANDLE_VALUE)
805   {
806     WARN(":failed-last error (%ld)\n",GetLastError());
807     __CRTDLL__set_errno(GetLastError());
808     return -1;
809   }
810
811   fd = __CRTDLL__alloc_fd(hand,ioflag);
812
813   TRACE(":fd (%d) handle (%d)\n",fd, hand);
814
815   if (flags & _IOAPPEND && fd > 0)
816     CRTDLL__lseek(fd, 0, FILE_END );
817
818   return fd;
819 }
820
821
822 /*********************************************************************
823  *                  _open_osfhandle         (CRTDLL.240)
824  *
825  * Create a file descriptor for a file HANDLE.
826  */
827 INT __cdecl CRTDLL__open_osfhandle(HANDLE hand, INT flags)
828 {
829   INT fd = __CRTDLL__alloc_fd(hand,flags);
830   TRACE(":handle (%d) fd (%d)\n",hand,fd);
831   return fd;
832 }
833
834
835 /*********************************************************************
836  *                  _putw         (CRTDLL.254)
837  *
838  * Write an int to a FILE*.
839  */
840 INT __cdecl CRTDLL__putw(INT val, CRTDLL_FILE* file)
841 {
842   return CRTDLL__write(file->_file, &val, sizeof(val)) == 1? val : EOF;
843 }
844
845
846 /*********************************************************************
847  *                  _read     (CRTDLL.256)
848  *
849  * Read data from a file.
850  */
851 INT __cdecl CRTDLL__read(INT fd, LPVOID buf, UINT count)
852 {
853   DWORD num_read;
854   HANDLE hand = __CRTDLL__fdtoh(fd);
855
856   /* Dont trace small reads, it gets *very* annoying */
857   if (count > 4)
858     TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
859   if (hand == INVALID_HANDLE_VALUE)
860     return -1;
861
862   /* Set _cnt to 0 so optimised binaries will call our implementation
863    * of putc/getc. See _filbuf/_flsbuf comments.
864    */
865   if (__CRTDLL_files[fd])
866     __CRTDLL_files[fd]->_cnt = 0;
867
868   if (ReadFile(hand, buf, count, &num_read, NULL))
869   {
870     if (num_read != count && __CRTDLL_files[fd])
871     {
872       TRACE(":EOF\n");
873       __CRTDLL_files[fd]->_flag |= _IOEOF;
874     }
875     return num_read;
876   }
877   TRACE(":failed-last error (%ld)\n",GetLastError());
878   if ( __CRTDLL_files[fd])
879      __CRTDLL_files[fd]->_flag |= _IOERR;
880   return -1;
881 }
882
883
884 /*********************************************************************
885  *                  _setmode           (CRTDLL.265)
886  *
887  * FIXME: At present we ignore the request to translate CR/LF to LF.
888  *
889  * We always translate when we read with fgets, we never do with fread
890  *
891  */
892 INT __cdecl CRTDLL__setmode(INT fd,INT mode)
893 {
894   if (mode & _O_TEXT)
895     FIXME("fd (%d) mode (%d) TEXT not implemented\n",fd,mode);
896   return 0;
897 }
898
899
900 /*********************************************************************
901  *                  _stat          (CRTDLL.280)
902  */
903 INT __cdecl CRTDLL__stat(const char* path, struct _stat * buf)
904 {
905   DWORD dw;
906   WIN32_FILE_ATTRIBUTE_DATA hfi;
907   unsigned short mode = CRTDLL_S_IREAD;
908   int plen;
909
910   TRACE(":file (%s) buf(%p)\n",path,buf);
911
912   if (!GetFileAttributesExA( path, GetFileExInfoStandard, &hfi ))
913   {
914       TRACE("failed-last error (%ld)\n",GetLastError());
915       __CRTDLL__set_errno(ERROR_FILE_NOT_FOUND);
916       return -1;
917   }
918
919   memset(buf,0,sizeof(struct _stat));
920
921   /* FIXME: rdev isnt drive num,despite what the docs say-what is it? */
922   if (isalpha(*path))
923     buf->st_dev = buf->st_rdev = toupper(*path - 'A'); /* drive num */
924   else
925     buf->st_dev = buf->st_rdev = CRTDLL__getdrive() - 1;
926
927   plen = strlen(path);
928
929   /* Dir, or regular file? */
930   if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
931       (path[plen-1] == '\\'))
932     mode |= (_S_IFDIR | CRTDLL_S_IEXEC);
933   else
934   {
935     mode |= _S_IFREG;
936     /* executable? */
937     if (plen > 6 && path[plen-4] == '.')  /* shortest exe: "\x.exe" */
938     {
939       unsigned int ext = tolower(path[plen-1]) | (tolower(path[plen-2]) << 8)
940         | (tolower(path[plen-3]) << 16);
941       if (ext == EXE || ext == BAT || ext == CMD || ext == COM)
942         mode |= CRTDLL_S_IEXEC;
943     }
944   }
945
946   if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
947     mode |= CRTDLL_S_IWRITE;
948
949   buf->st_mode  = mode;
950   buf->st_nlink = 1;
951   buf->st_size  = hfi.nFileSizeLow;
952   RtlTimeToSecondsSince1970( &hfi.ftLastAccessTime, &dw );
953   buf->st_atime = dw;
954   RtlTimeToSecondsSince1970( &hfi.ftLastWriteTime, &dw );
955   buf->st_mtime = buf->st_ctime = dw;
956   TRACE("\n%d %d %d %d %d %d\n", buf->st_mode,buf->st_nlink,buf->st_size,
957         buf->st_atime,buf->st_mtime, buf->st_ctime);
958   return 0;
959 }
960
961
962 /*********************************************************************
963  *                  _tell           (CRTDLL.302)
964  *
965  * Get current file position.
966  */
967 LONG __cdecl CRTDLL__tell(INT fd)
968 {
969   return CRTDLL__lseek(fd, 0, SEEK_CUR);
970 }
971
972
973 /*********************************************************************
974  *                  _tempnam           (CRTDLL.305)
975  * 
976  */
977 LPSTR __cdecl CRTDLL__tempnam(LPCSTR dir, LPCSTR prefix)
978 {
979   char tmpbuf[MAX_PATH];
980
981   TRACE("dir (%s) prefix (%s)\n",dir,prefix);
982   if (GetTempFileNameA(dir,prefix,0,tmpbuf))
983   {
984     TRACE("got name (%s)\n",tmpbuf);
985     return CRTDLL__strdup(tmpbuf);
986   }
987   TRACE("failed-last error (%ld)\n",GetLastError());
988   return NULL;
989 }
990
991
992 /*********************************************************************
993  *                  _umask           (CRTDLL.310)
994  *
995  * Set the process-wide umask.
996  */
997 INT __cdecl CRTDLL__umask(INT umask)
998 {
999   INT old_umask = __CRTDLL_umask;
1000   TRACE("umask (%d)\n",umask);
1001   __CRTDLL_umask = umask;
1002   return old_umask;
1003 }
1004
1005
1006 /*********************************************************************
1007  *                  _utime         (CRTDLL.314)
1008  * 
1009  * Set the file access/modification times on a file.
1010  */
1011 INT __cdecl CRTDLL__utime(LPCSTR path, struct _utimbuf *t)
1012 {
1013   INT fd = CRTDLL__open( path, _O_WRONLY | _O_BINARY );
1014
1015   if (fd > 0)
1016   {
1017     INT retVal = CRTDLL__futime(fd, t);
1018     CRTDLL__close(fd);
1019     return retVal;
1020   }
1021   return -1;
1022 }
1023
1024
1025 /*********************************************************************
1026  *                  _unlink           (CRTDLL.315)
1027  *
1028  * Delete a file.
1029  */
1030 INT __cdecl CRTDLL__unlink(LPCSTR path)
1031 {
1032   TRACE("path (%s)\n",path);
1033   if(DeleteFileA( path ))
1034     return 0;
1035
1036   TRACE("failed-last error (%ld)\n",GetLastError());
1037   __CRTDLL__set_errno(GetLastError());
1038   return -1;
1039 }
1040
1041
1042 /*********************************************************************
1043  *                  _write        (CRTDLL.332)
1044  *
1045  * Write data to a file.
1046  */
1047 UINT __cdecl CRTDLL__write(INT fd, LPCVOID buf, UINT count)
1048 {
1049   DWORD num_written;
1050   HANDLE hand = __CRTDLL__fdtoh(fd);
1051
1052   /* Dont trace small writes, it gets *very* annoying */
1053   if (count > 4)
1054     TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
1055   if (hand == INVALID_HANDLE_VALUE)
1056     return -1;
1057
1058   /* If appending, go to EOF */
1059   if (__CRTDLL_flags[fd] & _IOAPPEND)
1060     CRTDLL__lseek(fd, 0, FILE_END );
1061
1062   /* Set _cnt to 0 so optimised binaries will call our implementation
1063    * of putc/getc. See _filbuf/_flsbuf comments.
1064    */
1065   if (__CRTDLL_files[fd])
1066     __CRTDLL_files[fd]->_cnt = 0;
1067
1068   if (WriteFile(hand, buf, count, &num_written, NULL)
1069       &&  (num_written == count))
1070     return num_written;
1071
1072   TRACE(":failed-last error (%ld)\n",GetLastError());
1073   if ( __CRTDLL_files[fd])
1074      __CRTDLL_files[fd]->_flag |= _IOERR;
1075
1076   return -1;
1077 }
1078
1079
1080 /*********************************************************************
1081  *                  clearerr     (CRTDLL.349)
1082  *
1083  * Clear a FILE's error indicator.
1084  */
1085 VOID __cdecl CRTDLL_clearerr(CRTDLL_FILE* file)
1086 {
1087   TRACE(":file (%p) fd (%d)\n",file,file->_file);
1088   file->_flag &= ~(_IOERR | _IOEOF);
1089 }
1090
1091
1092 /*********************************************************************
1093  *                  fclose           (CRTDLL.362)
1094  *
1095  * Close an open file.
1096  */
1097 INT __cdecl CRTDLL_fclose( CRTDLL_FILE* file )
1098 {
1099   return CRTDLL__close(file->_file);
1100 }
1101
1102
1103 /*********************************************************************
1104  *                  feof           (CRTDLL.363)
1105  *
1106  * Check the eof indicator on a file.
1107  */
1108 INT __cdecl CRTDLL_feof( CRTDLL_FILE* file )
1109 {
1110   return file->_flag & _IOEOF;
1111 }
1112
1113
1114 /*********************************************************************
1115  *                  ferror         (CRTDLL.361)
1116  *
1117  * Check the error indicator on a file.
1118  */
1119 INT __cdecl CRTDLL_ferror( CRTDLL_FILE* file )
1120 {
1121   return file->_flag & _IOERR;
1122 }
1123
1124
1125 /*********************************************************************
1126  *                  fflush        (CRTDLL.362)
1127  */
1128 INT __cdecl CRTDLL_fflush( CRTDLL_FILE* file )
1129 {
1130   return CRTDLL__commit(file->_file);
1131 }
1132
1133
1134 /*********************************************************************
1135  *                  fgetc       (CRTDLL.363)
1136  */
1137 INT __cdecl CRTDLL_fgetc( CRTDLL_FILE* file )
1138 {
1139   char c;
1140   if (CRTDLL__read(file->_file,&c,1) != 1)
1141     return EOF;
1142   return c;
1143 }
1144
1145
1146 /*********************************************************************
1147  *                  fgetpos       (CRTDLL.364)
1148  */
1149 INT __cdecl CRTDLL_fgetpos( CRTDLL_FILE* file, fpos_t *pos)
1150 {
1151   *pos = CRTDLL__tell(file->_file);
1152   return (*pos == -1? -1 : 0);
1153 }
1154
1155
1156 /*********************************************************************
1157  *                  fgets       (CRTDLL.365)
1158  */
1159 CHAR* __cdecl CRTDLL_fgets(LPSTR s, INT size, CRTDLL_FILE* file)
1160 {
1161   int    cc;
1162   LPSTR  buf_start = s;
1163
1164   TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
1165         file,file->_file,s,size);
1166
1167   /* BAD, for the whole WINE process blocks... just done this way to test
1168    * windows95's ftp.exe.
1169    * JG - Is this true now we use ReadFile() on stdin too?
1170    */
1171   for(cc = CRTDLL_fgetc(file); cc != EOF && cc != '\n';
1172       cc = CRTDLL_fgetc(file))
1173     if (cc != '\r')
1174     {
1175       if (--size <= 0) break;
1176       *s++ = (char)cc;
1177     }
1178   if ((cc == EOF) && (s == buf_start)) /* If nothing read, return 0*/
1179   {
1180     TRACE(":nothing read\n");
1181     return 0;
1182   }
1183   if (cc == '\n')
1184     if (--size > 0)
1185       *s++ = '\n';
1186   *s = '\0';
1187   TRACE(":got '%s'\n", buf_start);
1188   return buf_start;
1189 }
1190
1191
1192 /*********************************************************************
1193  *                  fputs       (CRTDLL.375)
1194  */
1195 INT __cdecl CRTDLL_fputs( LPCSTR s, CRTDLL_FILE* file )
1196 {
1197   return CRTDLL_fwrite(s,strlen(s),1,file);
1198 }
1199
1200
1201 /*********************************************************************
1202  *                  fprintf       (CRTDLL.370)
1203  */
1204 INT __cdecl CRTDLL_fprintf( CRTDLL_FILE* file, LPCSTR format, ... )
1205 {
1206     va_list valist;
1207     INT res;
1208
1209     va_start( valist, format );
1210     res = CRTDLL_vfprintf( file, format, valist );
1211     va_end( valist );
1212     return res;
1213 }
1214
1215
1216 /*********************************************************************
1217  *                  fopen     (CRTDLL.372)
1218  *
1219  * Open a file.
1220  */
1221 CRTDLL_FILE* __cdecl CRTDLL_fopen(LPCSTR path, LPCSTR mode)
1222 {
1223   CRTDLL_FILE* file;
1224   INT flags = 0, plus = 0, fd;
1225   const char* search = mode;
1226
1227   TRACE(":path (%s) mode (%s)\n",path,mode);
1228
1229   while (*search)
1230     if (*search++ == '+')
1231       plus = 1;
1232
1233   /* map mode string to open() flags. "man fopen" for possibilities. */
1234   switch(*mode++)
1235   {
1236   case 'R': case 'r':
1237     flags = (plus ? _O_RDWR : _O_RDONLY);
1238     break;
1239   case 'W': case 'w':
1240     flags = _O_CREAT | _O_TRUNC | (plus  ? _O_RDWR : _O_WRONLY);
1241     break;
1242   case 'A': case 'a':
1243     flags = _O_CREAT | _O_APPEND | (plus  ? _O_RDWR : _O_WRONLY);
1244     break;
1245   default:
1246     return NULL;
1247   }
1248
1249   while (*mode)
1250     switch (*mode++)
1251     {
1252     case 'B': case 'b':
1253       flags |=  _O_BINARY;
1254       flags &= ~_O_TEXT;
1255       break;
1256     case 'T': case 't':
1257       flags |=  _O_TEXT;
1258       flags &= ~_O_BINARY;
1259       break;
1260     case '+':
1261       break;
1262     default:
1263       FIXME(":unknown flag %c not supported\n",mode[-1]);
1264     }
1265
1266   fd = CRTDLL__open(path, flags);
1267
1268   if (fd < 0)
1269     return NULL;
1270
1271   file = __CRTDLL__alloc_fp(fd);
1272   TRACE(":get file (%p)\n",file);
1273   if (!file)
1274     CRTDLL__close(fd);
1275
1276   return file;
1277 }
1278
1279
1280 /*********************************************************************
1281  *                  fputc       (CRTDLL.374)
1282  */
1283 INT __cdecl CRTDLL_fputc( INT c, CRTDLL_FILE* file )
1284 {
1285   return CRTDLL__write(file->_file, &c, 1) == 1? c : EOF;
1286 }
1287
1288
1289 /*********************************************************************
1290  *                  fread     (CRTDLL.377)
1291  */
1292 DWORD __cdecl CRTDLL_fread(LPVOID ptr, INT size, INT nmemb, CRTDLL_FILE* file)
1293 {
1294   DWORD read = CRTDLL__read(file->_file,ptr, size * nmemb);
1295   if (read <= 0)
1296     return 0;
1297   return read / size;
1298 }
1299
1300
1301 /*********************************************************************
1302  *                  freopen    (CRTDLL.379)
1303  * 
1304  */
1305 CRTDLL_FILE* __cdecl CRTDLL_freopen(LPCSTR path, LPCSTR mode,CRTDLL_FILE* file)
1306 {
1307   CRTDLL_FILE* newfile;
1308   INT fd;
1309
1310   TRACE(":path (%p) mode (%s) file (%p) fd (%d)\n",path,mode,file,file->_file);
1311   if (!file || ((fd = file->_file) < 0) || fd > __CRTDLL_fdend)
1312     return NULL;
1313
1314   if (fd > 2)
1315   {
1316     FIXME(":reopen on user file not implemented!\n");
1317     __CRTDLL__set_errno(ERROR_CALL_NOT_IMPLEMENTED);
1318     return NULL;
1319   }
1320
1321   /* first, create the new file */
1322   if ((newfile = CRTDLL_fopen(path,mode)) == NULL)
1323     return NULL;
1324
1325   if (fd < 3 && SetStdHandle(fd == 0 ? STD_INPUT_HANDLE :
1326      (fd == 1? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE),
1327       __CRTDLL_handles[newfile->_file]))
1328   {
1329     /* Redirecting std handle to file , copy over.. */
1330     __CRTDLL_handles[fd] = __CRTDLL_handles[newfile->_file];
1331     __CRTDLL_flags[fd] = __CRTDLL_flags[newfile->_file];
1332     memcpy(&__CRTDLL_iob[fd], newfile, sizeof (CRTDLL_FILE));
1333     __CRTDLL_iob[fd]._file = fd;
1334     /* And free up the resources allocated by fopen, but
1335      * not the HANDLE we copied. */
1336     CRTDLL_free(__CRTDLL_files[fd]);
1337     __CRTDLL__free_fd(newfile->_file);
1338     return &__CRTDLL_iob[fd];
1339   }
1340
1341   WARN(":failed-last error (%ld)\n",GetLastError());
1342   CRTDLL_fclose(newfile);
1343   __CRTDLL__set_errno(GetLastError());
1344   return NULL;
1345 }
1346
1347
1348 /*********************************************************************
1349  *                  fsetpos       (CRTDLL.380)
1350  */
1351 INT __cdecl CRTDLL_fsetpos( CRTDLL_FILE* file, fpos_t *pos)
1352 {
1353   return CRTDLL__lseek(file->_file,*pos,SEEK_SET);
1354 }
1355
1356
1357 /*********************************************************************
1358  *                  fscanf     (CRTDLL.381)
1359  */
1360 INT __cdecl CRTDLL_fscanf( CRTDLL_FILE* file, LPSTR format, ... )
1361 {
1362     INT rd = 0;
1363     int nch;
1364     va_list ap;
1365     if (!*format) return 0;
1366     WARN("%p (\"%s\"): semi-stub\n", file, format);
1367     nch = CRTDLL_fgetc(file);
1368     va_start(ap, format);
1369     while (*format) {
1370         if (*format == ' ') {
1371             /* skip whitespace */
1372             while ((nch!=EOF) && isspace(nch))
1373                 nch = CRTDLL_fgetc(file);
1374         }
1375         else if (*format == '%') {
1376             int st = 0;
1377             format++;
1378             switch(*format) {
1379             case 'd': { /* read an integer */
1380                     int*val = va_arg(ap, int*);
1381                     int cur = 0;
1382                     /* skip initial whitespace */
1383                     while ((nch!=EOF) && isspace(nch))
1384                         nch = CRTDLL_fgetc(file);
1385                     /* get sign and first digit */
1386                     if (nch == '-') {
1387                         nch = CRTDLL_fgetc(file);
1388                         if (isdigit(nch))
1389                             cur = -(nch - '0');
1390                         else break;
1391                     } else {
1392                         if (isdigit(nch))
1393                             cur = nch - '0';
1394                         else break;
1395                     }
1396                     nch = CRTDLL_fgetc(file);
1397                     /* read until no more digits */
1398                     while ((nch!=EOF) && isdigit(nch)) {
1399                         cur = cur*10 + (nch - '0');
1400                         nch = CRTDLL_fgetc(file);
1401                     }
1402                     st = 1;
1403                     *val = cur;
1404                 }
1405                 break;
1406             case 'f': { /* read a float */
1407                     float*val = va_arg(ap, float*);
1408                     float cur = 0;
1409                     /* skip initial whitespace */
1410                     while ((nch!=EOF) && isspace(nch))
1411                         nch = CRTDLL_fgetc(file);
1412                     /* get sign and first digit */
1413                     if (nch == '-') {
1414                         nch = CRTDLL_fgetc(file);
1415                         if (isdigit(nch))
1416                             cur = -(nch - '0');
1417                         else break;
1418                     } else {
1419                         if (isdigit(nch))
1420                             cur = nch - '0';
1421                         else break;
1422                     }
1423                     /* read until no more digits */
1424                     while ((nch!=EOF) && isdigit(nch)) {
1425                         cur = cur*10 + (nch - '0');
1426                         nch = CRTDLL_fgetc(file);
1427                     }
1428                     if (nch == '.') {
1429                         /* handle decimals */
1430                         float dec = 1;
1431                         nch = CRTDLL_fgetc(file);
1432                         while ((nch!=EOF) && isdigit(nch)) {
1433                             dec /= 10;
1434                             cur += dec * (nch - '0');
1435                             nch = CRTDLL_fgetc(file);
1436                         }
1437                     }
1438                     st = 1;
1439                     *val = cur;
1440                 }
1441                 break;
1442             case 's': { /* read a word */
1443                     char*str = va_arg(ap, char*);
1444                     char*sptr = str;
1445                     /* skip initial whitespace */
1446                     while ((nch!=EOF) && isspace(nch))
1447                         nch = CRTDLL_fgetc(file);
1448                     /* read until whitespace */
1449                     while ((nch!=EOF) && !isspace(nch)) {
1450                         *sptr++ = nch; st++;
1451                         nch = CRTDLL_fgetc(file);
1452                     }
1453                     /* terminate */
1454                     *sptr = 0;
1455                     TRACE("read word: %s\n", str);
1456                 }
1457                 break;
1458             default: FIXME("unhandled: %%%c\n", *format);
1459             }
1460             if (st) rd++;
1461             else break;
1462         }
1463         else {
1464             /* check for character match */
1465             if (nch == *format)
1466                nch = CRTDLL_fgetc(file);
1467             else break;
1468         }
1469         format++;
1470     }
1471     va_end(ap);
1472     if (nch!=EOF) {
1473         WARN("need ungetch\n");
1474     }
1475     TRACE("returning %d\n", rd);
1476     return rd;
1477 }
1478
1479
1480 /*********************************************************************
1481  *                  fseek     (CRTDLL.382)
1482  */
1483 LONG __cdecl CRTDLL_fseek( CRTDLL_FILE* file, LONG offset, INT whence)
1484 {
1485   return CRTDLL__lseek(file->_file,offset,whence);
1486 }
1487
1488
1489 /*********************************************************************
1490  *                  ftell     (CRTDLL.381)
1491  */
1492 LONG __cdecl CRTDLL_ftell( CRTDLL_FILE* file )
1493 {
1494   return CRTDLL__tell(file->_file);
1495 }
1496
1497
1498 /*********************************************************************
1499  *                  fwrite     (CRTDLL.383)
1500  */
1501 UINT __cdecl CRTDLL_fwrite( LPCVOID ptr, INT size, INT nmemb, CRTDLL_FILE* file )
1502 {
1503   UINT written = CRTDLL__write(file->_file, ptr, size * nmemb);
1504   if (written <= 0)
1505     return 0;
1506   return written / size;
1507 }
1508
1509
1510 /*********************************************************************
1511  *                  getchar       (CRTDLL.386)
1512  */
1513 INT __cdecl CRTDLL_getchar( VOID )
1514 {
1515   return CRTDLL_fgetc(CRTDLL_stdin);
1516 }
1517
1518
1519 /*********************************************************************
1520  *                  getc       (CRTDLL.388)
1521  */
1522 INT __cdecl CRTDLL_getc( CRTDLL_FILE* file )
1523 {
1524     return CRTDLL_fgetc( file );
1525 }
1526
1527
1528 /*********************************************************************
1529  *                  gets          (CRTDLL.391)
1530  */
1531 LPSTR __cdecl CRTDLL_gets(LPSTR buf)
1532 {
1533     int    cc;
1534     LPSTR  buf_start = buf;
1535
1536     /* BAD, for the whole WINE process blocks... just done this way to test
1537      * windows95's ftp.exe.
1538      * JG 19/9/00: Is this still true, now we are using ReadFile?
1539      */
1540     for(cc = CRTDLL_fgetc(CRTDLL_stdin); cc != EOF && cc != '\n';
1541         cc = CRTDLL_fgetc(CRTDLL_stdin))
1542         if(cc != '\r') *buf++ = (char)cc;
1543
1544     *buf = '\0';
1545
1546     TRACE("got '%s'\n", buf_start);
1547     return buf_start;
1548 }
1549
1550
1551 /*********************************************************************
1552  *                  putc       (CRTDLL.441)
1553  */
1554 INT __cdecl CRTDLL_putc( INT c, CRTDLL_FILE* file )
1555 {
1556   return CRTDLL_fputc( c, file );
1557 }
1558
1559
1560 /*********************************************************************
1561  *                  putchar       (CRTDLL.442)
1562  */
1563 void __cdecl CRTDLL_putchar( INT c )
1564 {
1565   CRTDLL_fputc(c, CRTDLL_stdout);
1566 }
1567
1568
1569 /*********************************************************************
1570  *                  puts       (CRTDLL.443)
1571  */
1572 INT __cdecl CRTDLL_puts(LPCSTR s)
1573 {
1574   return CRTDLL_fputs(s, CRTDLL_stdout);
1575 }
1576
1577
1578 /*********************************************************************
1579  *                  rewind     (CRTDLL.447)
1580  *
1581  * Set the file pointer to the start of a file and clear any error
1582  * indicators.
1583  */
1584 VOID __cdecl CRTDLL_rewind(CRTDLL_FILE* file)
1585 {
1586   TRACE(":file (%p) fd (%d)\n",file,file->_file);
1587   CRTDLL__lseek(file->_file,0,SEEK_SET);
1588   file->_flag &= ~(_IOEOF | _IOERR);
1589 }
1590
1591
1592 /*********************************************************************
1593  *                  remove           (CRTDLL.448)
1594  */
1595 INT __cdecl CRTDLL_remove(LPCSTR path)
1596 {
1597   TRACE(":path (%s)\n",path);
1598   if (DeleteFileA(path))
1599     return 0;
1600   TRACE(":failed-last error (%ld)\n",GetLastError());
1601   __CRTDLL__set_errno(GetLastError());
1602   return -1;
1603 }
1604
1605
1606 /*********************************************************************
1607  *                  rename           (CRTDLL.449)
1608  */
1609 INT __cdecl CRTDLL_rename(LPCSTR oldpath,LPCSTR newpath)
1610 {
1611   TRACE(":from %s to %s\n",oldpath,newpath);
1612   if (MoveFileExA( oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
1613     return 0;
1614   TRACE(":failed-last error (%ld)\n",GetLastError());
1615   __CRTDLL__set_errno(GetLastError());
1616   return -1;
1617 }
1618
1619
1620 /*********************************************************************
1621  *                  setbuf     (CRTDLL.452)
1622  */
1623 INT __cdecl CRTDLL_setbuf(CRTDLL_FILE* file, LPSTR buf)
1624 {
1625   TRACE(":file (%p) fd (%d) buf (%p)\n", file, file->_file,buf);
1626   if (buf)
1627     WARN(":user buffer will not be used!\n");
1628   /* FIXME: no buffering for now */
1629   return 0;
1630 }
1631
1632
1633 /*********************************************************************
1634  *                  tmpnam           (CRTDLL.490)
1635  *
1636  * lcclnk from lcc-win32 relies on a terminating dot in the name returned
1637  * 
1638  */
1639 LPSTR __cdecl CRTDLL_tmpnam(LPSTR s)
1640 {
1641   char tmpbuf[MAX_PATH];
1642   char* prefix = "TMP";
1643   if (!GetTempPathA(MAX_PATH,tmpbuf) ||
1644       !GetTempFileNameA(tmpbuf,prefix,0,CRTDLL_tmpname))
1645   {
1646     TRACE(":failed-last error (%ld)\n",GetLastError());
1647     return NULL;
1648   }
1649   TRACE(":got tmpnam %s\n",CRTDLL_tmpname);
1650   s = CRTDLL_tmpname;
1651   return s;
1652 }
1653
1654
1655 /*********************************************************************
1656  *                  vfprintf       (CRTDLL.494)
1657  *
1658  * Write formatted output to a file.
1659  */
1660
1661 /* we have avoided libc stdio.h so far, lets not start now */
1662 extern int vsprintf(void *, const void *, va_list);
1663
1664 /********************************************************************/
1665
1666 INT __cdecl CRTDLL_vfprintf( CRTDLL_FILE* file, LPCSTR format, va_list args )
1667 {
1668   /* FIXME: We should parse the format string, calculate the maximum,
1669    * length of each arg, malloc a buffer, print to it, and fwrite that.
1670    * Yes this sucks, but not as much as crashing 1/2 way through an
1671    * app writing to a file :-(
1672    */
1673   char buffer[2048];
1674   TRACE(":file (%p) fd (%d) fmt (%s)\n",file,file->_file,format);
1675
1676   vsprintf( buffer, format, args );
1677   return CRTDLL_fwrite( buffer, 1, strlen(buffer), file );
1678 }
1679