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