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