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