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