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