2 * msvcrt.dll file functions
4 * Copyright 1996,1998 Marcus Meissner
5 * Copyright 1996 Jukka Iivonen
6 * Copyright 1997,2000 Uwe Bonnes
7 * Copyright 2000 Jon Griffiths
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.
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.
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
31 #include "wine/unicode.h"
32 #include "msvcrt/direct.h"
33 #include "msvcrt/fcntl.h"
34 #include "msvcrt/io.h"
35 #include "msvcrt/sys/locking.h"
36 #include "msvcrt/stdio.h"
37 #include "msvcrt/stdlib.h"
38 #include "msvcrt/string.h"
39 #include "msvcrt/sys/stat.h"
40 #include "msvcrt/sys/utime.h"
41 #include "msvcrt/time.h"
42 #include "msvcrt/share.h"
44 #include "wine/debug.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
48 /* for stat mode, permissions apply to all,owner and group */
49 #define MSVCRT_S_IREAD (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6))
50 #define MSVCRT_S_IWRITE (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6))
51 #define MSVCRT_S_IEXEC (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6))
53 /* _access() bit flags FIXME: incomplete */
54 #define MSVCRT_W_OK 0x02
57 /* FIXME: Make this dynamic */
58 #define MSVCRT_MAX_FILES 257
60 HANDLE MSVCRT_handles[MSVCRT_MAX_FILES];
61 MSVCRT_FILE* MSVCRT_files[MSVCRT_MAX_FILES];
62 int MSVCRT_flags[MSVCRT_MAX_FILES];
63 char *MSVCRT_tempfiles[MSVCRT_MAX_FILES];
64 MSVCRT_FILE MSVCRT__iob[3];
65 #define MSVCRT_stdin (MSVCRT__iob+STDIN_FILENO)
66 #define MSVCRT_stdout (MSVCRT__iob+STDOUT_FILENO)
67 #define MSVCRT_stderr (MSVCRT__iob+STDERR_FILENO)
69 static int MSVCRT_fdstart = 3; /* first unallocated fd */
70 static int MSVCRT_fdend = 3; /* highest allocated fd */
72 /* INTERNAL: process umask */
73 static int MSVCRT_umask = 0;
75 /* INTERNAL: Static buffer for temp file name */
76 static char MSVCRT_tmpname[MAX_PATH];
78 static const unsigned int EXE = 'e' << 16 | 'x' << 8 | 'e';
79 static const unsigned int BAT = 'b' << 16 | 'a' << 8 | 't';
80 static const unsigned int CMD = 'c' << 16 | 'm' << 8 | 'd';
81 static const unsigned int COM = 'c' << 16 | 'o' << 8 | 'm';
83 #define TOUL(x) (ULONGLONG)((WCHAR)L##x)
84 static const ULONGLONG WCEXE = TOUL('e') << 32 | TOUL('x') << 16 | TOUL('e');
85 static const ULONGLONG WCBAT = TOUL('b') << 32 | TOUL('a') << 16 | TOUL('t');
86 static const ULONGLONG WCCMD = TOUL('c') << 32 | TOUL('m') << 16 | TOUL('d');
87 static const ULONGLONG WCCOM = TOUL('c') << 32 | TOUL('o') << 16 | TOUL('m');
89 extern CRITICAL_SECTION MSVCRT_file_cs;
90 #define LOCK_FILES EnterCriticalSection(&MSVCRT_file_cs)
91 #define UNLOCK_FILES LeaveCriticalSection(&MSVCRT_file_cs)
94 /* INTERNAL: Get the HANDLE for a fd */
95 static HANDLE msvcrt_fdtoh(int fd)
97 if (fd < 0 || fd >= MSVCRT_fdend ||
98 MSVCRT_handles[fd] == INVALID_HANDLE_VALUE)
100 WARN(":fd (%d) - no handle!\n",fd);
101 SET_THREAD_VAR(doserrno,0);
102 SET_THREAD_VAR(errno,MSVCRT_EBADF);
103 return INVALID_HANDLE_VALUE;
105 return MSVCRT_handles[fd];
108 /* INTERNAL: free a file entry fd */
109 static void msvcrt_free_fd(int fd)
111 MSVCRT_handles[fd] = INVALID_HANDLE_VALUE;
112 MSVCRT_files[fd] = 0;
113 MSVCRT_flags[fd] = 0;
114 TRACE(":fd (%d) freed\n",fd);
116 return; /* dont use 0,1,2 for user files */
117 if (fd == MSVCRT_fdend - 1)
119 if (fd < MSVCRT_fdstart)
123 /* INTERNAL: Allocate an fd slot from a Win32 HANDLE */
124 static int msvcrt_alloc_fd(HANDLE hand, int flag)
126 int fd = MSVCRT_fdstart;
128 TRACE(":handle (%d) allocating fd (%d)\n",hand,fd);
129 if (fd >= MSVCRT_MAX_FILES)
131 WARN(":files exhausted!\n");
134 MSVCRT_handles[fd] = hand;
135 MSVCRT_flags[fd] = flag;
137 /* locate next free slot */
138 if (fd == MSVCRT_fdend)
139 MSVCRT_fdstart = ++MSVCRT_fdend;
141 while(MSVCRT_fdstart < MSVCRT_fdend &&
142 MSVCRT_handles[MSVCRT_fdstart] != INVALID_HANDLE_VALUE)
148 /* INTERNAL: Allocate a FILE* for an fd slot
149 * This is done lazily to avoid memory wastage for low level open/write
150 * usage when a FILE* is not requested (but may be later).
152 static MSVCRT_FILE* msvcrt_alloc_fp(int fd)
154 TRACE(":fd (%d) allocating FILE*\n",fd);
155 if (fd < 0 || fd >= MSVCRT_fdend ||
156 MSVCRT_handles[fd] == INVALID_HANDLE_VALUE)
158 WARN(":invalid fd %d\n",fd);
159 SET_THREAD_VAR(doserrno,0);
160 SET_THREAD_VAR(errno,MSVCRT_EBADF);
163 if (!MSVCRT_files[fd])
165 if ((MSVCRT_files[fd] = MSVCRT_calloc(sizeof(MSVCRT_FILE),1)))
167 MSVCRT_files[fd]->_file = fd;
168 MSVCRT_files[fd]->_flag = MSVCRT_flags[fd];
169 MSVCRT_files[fd]->_flag &= ~MSVCRT__IOAPPEND; /* mask out, see above */
172 TRACE(":got FILE* (%p)\n",MSVCRT_files[fd]);
173 return MSVCRT_files[fd];
177 /* INTERNAL: Set up stdin, stderr and stdout */
178 void msvcrt_init_io(void)
181 memset(MSVCRT__iob,0,3*sizeof(MSVCRT_FILE));
182 MSVCRT_handles[0] = GetStdHandle(STD_INPUT_HANDLE);
183 MSVCRT_flags[0] = MSVCRT__iob[0]._flag = MSVCRT__IOREAD;
184 MSVCRT_handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
185 MSVCRT_flags[1] = MSVCRT__iob[1]._flag = MSVCRT__IOWRT;
186 MSVCRT_handles[2] = GetStdHandle(STD_ERROR_HANDLE);
187 MSVCRT_flags[2] = MSVCRT__iob[2]._flag = MSVCRT__IOWRT;
189 TRACE(":handles (%d)(%d)(%d)\n",MSVCRT_handles[0],
190 MSVCRT_handles[1],MSVCRT_handles[2]);
192 for (i = 0; i < 3; i++)
194 /* FILE structs for stdin/out/err are static and never deleted */
195 MSVCRT_files[i] = &MSVCRT__iob[i];
196 MSVCRT__iob[i]._file = i;
197 MSVCRT_tempfiles[i] = NULL;
201 /* INTERNAL: Flush stdio file buffer */
202 static int msvcrt_flush_buffer(MSVCRT_FILE* file)
205 int cnt=file->_ptr-file->_base;
206 if(cnt>0 && _write(file->_file, file->_base, cnt) != cnt) {
209 file->_ptr=file->_base;
210 file->_cnt=file->_bufsiz;
215 /* INTERNAL: Allocate stdio file buffer */
216 static void msvcrt_alloc_buffer(MSVCRT_FILE* file)
218 file->_base = MSVCRT_calloc(MSVCRT_BUFSIZ,1);
220 file->_bufsiz = MSVCRT_BUFSIZ;
221 file->_flag |= MSVCRT__IOMYBUF;
223 file->_base = (unsigned char *)(&file->_charbuf);
225 file->_bufsiz = sizeof(file->_charbuf);
227 file->_ptr = file->_base;
231 /*********************************************************************
234 MSVCRT_FILE *__p__iob(void)
236 return &MSVCRT__iob[0];
239 /*********************************************************************
242 int _access(const char *filename, int mode)
244 DWORD attr = GetFileAttributesA(filename);
246 TRACE("(%s,%d) %ld\n",filename,mode,attr);
248 if (!filename || attr == 0xffffffff)
250 MSVCRT__set_errno(GetLastError());
253 if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
255 MSVCRT__set_errno(ERROR_ACCESS_DENIED);
261 /*********************************************************************
262 * _waccess (MSVCRT.@)
264 int _waccess(const WCHAR *filename, int mode)
266 DWORD attr = GetFileAttributesW(filename);
268 TRACE("(%s,%d) %ld\n",debugstr_w(filename),mode,attr);
270 if (!filename || attr == 0xffffffff)
272 MSVCRT__set_errno(GetLastError());
275 if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
277 MSVCRT__set_errno(ERROR_ACCESS_DENIED);
283 /*********************************************************************
286 int _chmod(const char *path, int flags)
288 DWORD oldFlags = GetFileAttributesA(path);
290 if (oldFlags != 0x0FFFFFFFF)
292 DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
293 oldFlags | FILE_ATTRIBUTE_READONLY;
295 if (newFlags == oldFlags || SetFileAttributesA(path, newFlags))
298 MSVCRT__set_errno(GetLastError());
302 /*********************************************************************
305 int _wchmod(const WCHAR *path, int flags)
307 DWORD oldFlags = GetFileAttributesW(path);
309 if (oldFlags != 0x0FFFFFFFF)
311 DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
312 oldFlags | FILE_ATTRIBUTE_READONLY;
314 if (newFlags == oldFlags || SetFileAttributesW(path, newFlags))
317 MSVCRT__set_errno(GetLastError());
321 /*********************************************************************
324 int _unlink(const char *path)
326 TRACE("(%s)\n",path);
327 if(DeleteFileA(path))
329 TRACE("failed (%ld)\n",GetLastError());
330 MSVCRT__set_errno(GetLastError());
334 /*********************************************************************
335 * _wunlink (MSVCRT.@)
337 int _wunlink(const WCHAR *path)
339 TRACE("(%s)\n",debugstr_w(path));
340 if(DeleteFileW(path))
342 TRACE("failed (%ld)\n",GetLastError());
343 MSVCRT__set_errno(GetLastError());
347 /*********************************************************************
352 HANDLE hand = msvcrt_fdtoh(fd);
354 TRACE(":fd (%d) handle (%d)\n",fd,hand);
355 if (hand == INVALID_HANDLE_VALUE)
357 /* flush stdio buffers */
358 if(MSVCRT_files[fd]) {
359 if(MSVCRT_files[fd]->_flag & MSVCRT__IOWRT)
360 MSVCRT_fflush(MSVCRT_files[fd]);
362 if(MSVCRT_files[fd]->_flag & MSVCRT__IOMYBUF)
363 MSVCRT_free(MSVCRT_files[fd]->_base);
366 /* Dont free std FILE*'s, they are not dynamic */
367 if (fd > 2 && MSVCRT_files[fd])
368 MSVCRT_free(MSVCRT_files[fd]);
372 if (!CloseHandle(hand))
374 WARN(":failed-last error (%ld)\n",GetLastError());
375 MSVCRT__set_errno(GetLastError());
378 if (MSVCRT_tempfiles[fd])
380 TRACE("deleting temporary file '%s'\n",MSVCRT_tempfiles[fd]);
381 _unlink(MSVCRT_tempfiles[fd]);
382 MSVCRT_free(MSVCRT_tempfiles[fd]);
383 MSVCRT_tempfiles[fd] = NULL;
390 /*********************************************************************
395 HANDLE hand = msvcrt_fdtoh(fd);
397 TRACE(":fd (%d) handle (%d)\n",fd,hand);
398 if (hand == INVALID_HANDLE_VALUE)
401 if (!FlushFileBuffers(hand))
403 if (GetLastError() == ERROR_INVALID_HANDLE)
405 /* FlushFileBuffers fails for console handles
406 * so we ignore this error.
410 TRACE(":failed-last error (%ld)\n",GetLastError());
411 MSVCRT__set_errno(GetLastError());
418 /*********************************************************************
424 HANDLE hand = msvcrt_fdtoh(fd);
426 TRACE(":fd (%d) handle (%d)\n",fd,hand);
428 if (hand == INVALID_HANDLE_VALUE)
431 /* If we have a FILE* for this file, the EOF flag
432 * will be set by the read()/write() functions.
434 if (MSVCRT_files[fd])
435 return MSVCRT_flags[fd] & MSVCRT__IOEOF;
437 /* Otherwise we do it the hard way */
438 curpos = SetFilePointer(hand, 0, NULL, SEEK_CUR);
439 endpos = SetFilePointer(hand, 0, NULL, FILE_END);
441 if (curpos == endpos)
444 SetFilePointer(hand, curpos, 0, FILE_BEGIN);
448 /*********************************************************************
449 * _fcloseall (MSVCRT.@)
453 int num_closed = 0, i;
455 for (i = 3; i < MSVCRT_fdend; i++)
456 if (MSVCRT_handles[i] != INVALID_HANDLE_VALUE)
462 TRACE(":closed (%d) handles\n",num_closed);
466 /*********************************************************************
469 LONG _lseek(int fd, LONG offset, int whence)
472 HANDLE hand = msvcrt_fdtoh(fd);
474 TRACE(":fd (%d) handle (%d)\n",fd,hand);
475 if (hand == INVALID_HANDLE_VALUE)
478 if (whence < 0 || whence > 2)
480 SET_THREAD_VAR(errno,MSVCRT_EINVAL);
484 TRACE(":fd (%d) to 0x%08lx pos %s\n",
485 fd,offset,(whence==SEEK_SET)?"SEEK_SET":
486 (whence==SEEK_CUR)?"SEEK_CUR":
487 (whence==SEEK_END)?"SEEK_END":"UNKNOWN");
489 if ((ret = SetFilePointer(hand, offset, NULL, whence)) != 0xffffffff)
491 if (MSVCRT_files[fd])
492 MSVCRT_files[fd]->_flag &= ~MSVCRT__IOEOF;
493 /* FIXME: What if we seek _to_ EOF - is EOF set? */
496 TRACE(":error-last error (%ld)\n",GetLastError());
497 if (MSVCRT_files[fd])
498 switch(GetLastError())
500 case ERROR_NEGATIVE_SEEK:
501 case ERROR_SEEK_ON_DEVICE:
502 MSVCRT__set_errno(GetLastError());
503 MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
511 /*********************************************************************
512 * _locking (MSVCRT.@)
514 * This is untested; the underlying LockFile doesn't work yet.
516 int _locking(int fd, int mode, LONG nbytes)
520 HANDLE hand = msvcrt_fdtoh(fd);
522 TRACE(":fd (%d) handle (%d)\n",fd,hand);
523 if (hand == INVALID_HANDLE_VALUE)
526 if (mode < 0 || mode > 4)
528 SET_THREAD_VAR(errno,MSVCRT_EINVAL);
532 TRACE(":fd (%d) by 0x%08lx mode %s\n",
533 fd,nbytes,(mode==_LK_UNLCK)?"_LK_UNLCK":
534 (mode==_LK_LOCK)?"_LK_LOCK":
535 (mode==_LK_NBLCK)?"_LK_NBLCK":
536 (mode==_LK_RLCK)?"_LK_RLCK":
537 (mode==_LK_NBRLCK)?"_LK_NBRLCK":
540 if ((cur_locn = SetFilePointer(hand, 0L, NULL, SEEK_CUR)) == 0xffffffff)
542 FIXME ("Seek failed\n");
543 SET_THREAD_VAR(errno,MSVCRT_EINVAL); /* FIXME */
546 if (mode == _LK_LOCK || mode == _LK_RLCK)
549 ret = 1; /* just to satisfy gcc */
552 ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
557 else if (mode == _LK_UNLCK)
558 ret = UnlockFile(hand, cur_locn, 0L, nbytes, 0L);
560 ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
561 /* FIXME - what about error settings? */
565 /*********************************************************************
568 void MSVCRT_rewind(MSVCRT_FILE* file)
570 TRACE(":file (%p) fd (%d)\n",file,file->_file);
571 MSVCRT_fseek(file, 0L, SEEK_SET);
572 MSVCRT_clearerr(file);
575 /*********************************************************************
578 MSVCRT_FILE* _fdopen(int fd, const char *mode)
580 MSVCRT_FILE* file = msvcrt_alloc_fp(fd);
582 TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,mode,file);
589 /*********************************************************************
590 * _wfdopen (MSVCRT.@)
592 MSVCRT_FILE* _wfdopen(int fd, const WCHAR *mode)
594 MSVCRT_FILE* file = msvcrt_alloc_fp(fd);
596 TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,debugstr_w(mode),file);
603 /*********************************************************************
604 * _filelength (MSVCRT.@)
606 LONG _filelength(int fd)
608 LONG curPos = _lseek(fd, 0, SEEK_CUR);
611 LONG endPos = _lseek(fd, 0, SEEK_END);
614 if (endPos != curPos)
615 _lseek(fd, curPos, SEEK_SET);
622 /*********************************************************************
625 int _fileno(MSVCRT_FILE* file)
627 TRACE(":FILE* (%p) fd (%d)\n",file,file->_file);
631 /*********************************************************************
632 * _flushall (MSVCRT.@)
636 int num_flushed = 0, i = 3;
638 while(i < MSVCRT_fdend)
639 if (MSVCRT_handles[i] != INVALID_HANDLE_VALUE)
642 /* FIXME: flush, do not commit */
643 if (_commit(i) == -1)
645 MSVCRT_files[i]->_flag |= MSVCRT__IOERR;
647 if(MSVCRT_files[i] && MSVCRT_files[i]->_flag & MSVCRT__IOWRT) {
648 MSVCRT_fflush(MSVCRT_files[i]);
653 TRACE(":flushed (%d) handles\n",num_flushed);
657 /*********************************************************************
660 int _fstat(int fd, struct _stat* buf)
663 BY_HANDLE_FILE_INFORMATION hfi;
664 HANDLE hand = msvcrt_fdtoh(fd);
666 TRACE(":fd (%d) stat (%p)\n",fd,buf);
667 if (hand == INVALID_HANDLE_VALUE)
672 WARN(":failed-NULL buf\n");
673 MSVCRT__set_errno(ERROR_INVALID_PARAMETER);
677 memset(&hfi, 0, sizeof(hfi));
678 memset(buf, 0, sizeof(struct _stat));
679 if (!GetFileInformationByHandle(hand, &hfi))
681 WARN(":failed-last error (%ld)\n",GetLastError());
682 MSVCRT__set_errno(ERROR_INVALID_PARAMETER);
685 FIXME(":dwFileAttributes = %ld, mode set to 0\n",hfi.dwFileAttributes);
686 buf->st_nlink = hfi.nNumberOfLinks;
687 buf->st_size = hfi.nFileSizeLow;
688 RtlTimeToSecondsSince1970(&hfi.ftLastAccessTime, &dw);
690 RtlTimeToSecondsSince1970(&hfi.ftLastWriteTime, &dw);
691 buf->st_mtime = buf->st_ctime = dw;
695 /*********************************************************************
698 int _futime(int fd, struct _utimbuf *t)
700 HANDLE hand = msvcrt_fdtoh(fd);
705 MSVCRT_time_t currTime;
706 MSVCRT_time(&currTime);
707 RtlSecondsSince1970ToTime(currTime, &at);
708 memcpy(&wt, &at, sizeof(wt));
712 RtlSecondsSince1970ToTime(t->actime, &at);
713 if (t->actime == t->modtime)
714 memcpy(&wt, &at, sizeof(wt));
716 RtlSecondsSince1970ToTime(t->modtime, &wt);
719 if (!SetFileTime(hand, NULL, &at, &wt))
721 MSVCRT__set_errno(GetLastError());
727 /*********************************************************************
728 * _get_osfhandle (MSVCRT.@)
730 long _get_osfhandle(int fd)
732 HANDLE hand = msvcrt_fdtoh(fd);
733 HANDLE newhand = hand;
734 TRACE(":fd (%d) handle (%d)\n",fd,hand);
736 if (hand != INVALID_HANDLE_VALUE)
738 /* FIXME: I'm not convinced that I should be copying the
739 * handle here - it may be leaked if the app doesn't
740 * close it (and the API docs dont say that it should)
741 * Not duplicating it means that it can't be inherited
742 * and so lcc's wedit doesn't cope when it passes it to
743 * child processes. I've an idea that it should either
744 * be copied by CreateProcess, or marked as inheritable
745 * when initialised, or maybe both? JG 21-9-00.
747 DuplicateHandle(GetCurrentProcess(),hand,GetCurrentProcess(),
748 &newhand,0,TRUE,DUPLICATE_SAME_ACCESS);
753 /*********************************************************************
758 HANDLE hand = msvcrt_fdtoh(fd);
760 TRACE(":fd (%d) handle (%d)\n",fd,hand);
761 if (hand == INVALID_HANDLE_VALUE)
764 return GetFileType(hand) == FILE_TYPE_CHAR? 1 : 0;
767 /*********************************************************************
770 char *_mktemp(char *pattern)
773 char *retVal = pattern;
778 numX = (*pattern++ == 'X')? numX + 1 : 0;
782 id = GetCurrentProcessId();
786 int tempNum = id / 10;
787 *pattern-- = id - (tempNum * 10) + '0';
793 if (GetFileAttributesA(retVal) == 0xFFFFFFFF &&
794 GetLastError() == ERROR_FILE_NOT_FOUND)
797 } while(letter != '|');
801 /*********************************************************************
802 * _wmktemp (MSVCRT.@)
804 WCHAR *_wmktemp(WCHAR *pattern)
807 WCHAR *retVal = pattern;
809 WCHAR letter = (WCHAR)L'a';
812 numX = (*pattern++ == (WCHAR)L'X')? numX + 1 : 0;
816 id = GetCurrentProcessId();
820 int tempNum = id / 10;
821 *pattern-- = id - (tempNum * 10) + (WCHAR)L'0';
827 if (GetFileAttributesW(retVal) == 0xFFFFFFFF &&
828 GetLastError() == ERROR_FILE_NOT_FOUND)
831 } while(letter != (WCHAR)L'|');
835 /*********************************************************************
838 int MSVCRT__sopen( const char *path, int oflags, int shflags, ... )
842 DWORD access = 0, creation = 0;
846 SECURITY_ATTRIBUTES sa;
849 TRACE(":file (%s) oflags: 0x%04x shflags: 0x%04x\n",
850 path, oflags, shflags);
852 switch(oflags & (_O_RDONLY | _O_WRONLY | _O_RDWR))
855 access |= GENERIC_READ;
856 ioflag |= MSVCRT__IOREAD;
859 access |= GENERIC_WRITE;
860 ioflag |= MSVCRT__IOWRT;
863 access |= GENERIC_WRITE | GENERIC_READ;
864 ioflag |= MSVCRT__IORW;
868 if (oflags & _O_CREAT)
870 va_start(ap, shflags);
871 pmode = va_arg(ap, int);
874 FIXME(": pmode 0x%04x ignored\n", pmode);
876 if (oflags & _O_EXCL)
877 creation = CREATE_NEW;
878 else if (oflags & _O_TRUNC)
879 creation = CREATE_ALWAYS;
881 creation = OPEN_ALWAYS;
883 else /* no _O_CREAT */
885 if (oflags & _O_TRUNC)
886 creation = TRUNCATE_EXISTING;
888 creation = OPEN_EXISTING;
890 if (oflags & _O_APPEND)
891 ioflag |= MSVCRT__IOAPPEND;
894 oflags |= _O_BINARY; /* FIXME: Default to text */
896 if (oflags & _O_TEXT)
898 /* Dont warn when writing */
899 if (ioflag & GENERIC_READ)
900 FIXME(":TEXT node not implemented\n");
910 sharing = FILE_SHARE_READ;
913 sharing = FILE_SHARE_WRITE;
916 sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
919 ERR( "Unhandled shflags 0x%x\n", shflags );
923 if (oflags & ~(_O_BINARY|_O_TEXT|_O_APPEND|_O_TRUNC|_O_EXCL
924 |_O_CREAT|_O_RDWR|_O_TEMPORARY|_O_NOINHERIT))
925 TRACE(":unsupported oflags 0x%04x\n",oflags);
927 sa.nLength = sizeof( SECURITY_ATTRIBUTES );
928 sa.lpSecurityDescriptor = NULL;
929 sa.bInheritHandle = (oflags & _O_NOINHERIT) ? FALSE : TRUE;
931 hand = CreateFileA(path, access, sharing,
932 &sa, creation, FILE_ATTRIBUTE_NORMAL, 0);
934 if (hand == INVALID_HANDLE_VALUE) {
935 WARN(":failed-last error (%ld)\n",GetLastError());
936 MSVCRT__set_errno(GetLastError());
940 fd = msvcrt_alloc_fd(hand, ioflag);
942 TRACE(":fd (%d) handle (%d)\n",fd, hand);
946 if (oflags & _O_TEMPORARY)
947 MSVCRT_tempfiles[fd] = _strdup(path);
948 if (ioflag & MSVCRT__IOAPPEND)
949 _lseek(fd, 0, FILE_END);
955 /*********************************************************************
958 int MSVCRT__wsopen( const WCHAR* path, int oflags, int shflags, ... )
960 const unsigned int len = strlenW(path);
961 char *patha = MSVCRT_calloc(len + 1,1);
965 va_start(ap, shflags);
966 pmode = va_arg(ap, int);
969 if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
971 int retval = MSVCRT__sopen(patha,oflags,shflags,pmode);
976 MSVCRT__set_errno(GetLastError());
980 /*********************************************************************
983 int _open( const char *path, int flags, ... )
989 pmode = va_arg(ap, int);
992 return MSVCRT__sopen( path, flags, _SH_DENYNO, pmode );
995 /*********************************************************************
998 int _wopen(const WCHAR *path,int flags,...)
1000 const unsigned int len = strlenW(path);
1001 char *patha = MSVCRT_calloc(len + 1,1);
1005 va_start(ap, flags);
1006 pmode = va_arg(ap, int);
1009 if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
1011 int retval = _open(patha,flags,pmode);
1016 MSVCRT__set_errno(GetLastError());
1020 /*********************************************************************
1023 int _creat(const char *path, int flags)
1025 int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
1026 return _open(path, usedFlags);
1029 /*********************************************************************
1030 * _wcreat (MSVCRT.@)
1032 int _wcreat(const WCHAR *path, int flags)
1034 int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
1035 return _wopen(path, usedFlags);
1038 /*********************************************************************
1039 * _open_osfhandle (MSVCRT.@)
1041 int _open_osfhandle(long hand, int flags)
1043 int fd = msvcrt_alloc_fd(hand,flags);
1044 TRACE(":handle (%ld) fd (%d)\n",hand,fd);
1048 /*********************************************************************
1053 int num_removed = 0, i;
1055 for (i = 3; i < MSVCRT_fdend; i++)
1056 if (MSVCRT_tempfiles[i])
1063 TRACE(":removed (%d) temp files\n",num_removed);
1067 /*********************************************************************
1070 int _read(int fd, void *buf, unsigned int count)
1073 HANDLE hand = msvcrt_fdtoh(fd);
1075 /* Dont trace small reads, it gets *very* annoying */
1077 TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
1078 if (hand == INVALID_HANDLE_VALUE)
1081 if (ReadFile(hand, buf, count, &num_read, NULL))
1083 if (num_read != count && MSVCRT_files[fd])
1086 MSVCRT_flags[fd] |= MSVCRT__IOEOF;
1088 MSVCRT_files[fd]->_flag |= MSVCRT__IOEOF;
1093 TRACE(":failed-last error (%ld)\n",GetLastError());
1094 if (MSVCRT_files[fd])
1095 MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
1099 /*********************************************************************
1102 int _getw(MSVCRT_FILE* file)
1105 if (_read(file->_file, &i, sizeof(int)) != 1)
1110 /*********************************************************************
1111 * _setmode (MSVCRT.@)
1113 int _setmode(int fd,int mode)
1116 FIXME("fd (%d) mode (%d) TEXT not implemented\n",fd,mode);
1120 /*********************************************************************
1123 int _stat(const char* path, struct _stat * buf)
1126 WIN32_FILE_ATTRIBUTE_DATA hfi;
1127 unsigned short mode = MSVCRT_S_IREAD;
1130 TRACE(":file (%s) buf(%p)\n",path,buf);
1132 if (!GetFileAttributesExA(path, GetFileExInfoStandard, &hfi))
1134 TRACE("failed (%ld)\n",GetLastError());
1135 MSVCRT__set_errno(ERROR_FILE_NOT_FOUND);
1139 memset(buf,0,sizeof(struct _stat));
1141 /* FIXME: rdev isnt drive num,despite what the docs say-what is it?
1142 Bon 011120: This FIXME seems incorrect
1143 Also a letter as first char isn't enough to be classify
1146 if (isalpha(*path)&& (*(path+1)==':'))
1147 buf->st_dev = buf->st_rdev = toupper(*path) - 'A'; /* drive num */
1149 buf->st_dev = buf->st_rdev = _getdrive() - 1;
1151 plen = strlen(path);
1153 /* Dir, or regular file? */
1154 if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1155 (path[plen-1] == '\\'))
1156 mode |= (_S_IFDIR | MSVCRT_S_IEXEC);
1161 if (plen > 6 && path[plen-4] == '.') /* shortest exe: "\x.exe" */
1163 unsigned int ext = tolower(path[plen-1]) | (tolower(path[plen-2]) << 8) |
1164 (tolower(path[plen-3]) << 16);
1165 if (ext == EXE || ext == BAT || ext == CMD || ext == COM)
1166 mode |= MSVCRT_S_IEXEC;
1170 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1171 mode |= MSVCRT_S_IWRITE;
1173 buf->st_mode = mode;
1175 buf->st_size = hfi.nFileSizeLow;
1176 RtlTimeToSecondsSince1970(&hfi.ftLastAccessTime, &dw);
1178 RtlTimeToSecondsSince1970(&hfi.ftLastWriteTime, &dw);
1179 buf->st_mtime = buf->st_ctime = dw;
1180 TRACE("\n%d %d %d %ld %ld %ld\n", buf->st_mode,buf->st_nlink,buf->st_size,
1181 buf->st_atime,buf->st_mtime, buf->st_ctime);
1185 /*********************************************************************
1188 int _wstat(const WCHAR* path, struct _stat * buf)
1191 WIN32_FILE_ATTRIBUTE_DATA hfi;
1192 unsigned short mode = MSVCRT_S_IREAD;
1195 TRACE(":file (%s) buf(%p)\n",debugstr_w(path),buf);
1197 if (!GetFileAttributesExW(path, GetFileExInfoStandard, &hfi))
1199 TRACE("failed (%ld)\n",GetLastError());
1200 MSVCRT__set_errno(ERROR_FILE_NOT_FOUND);
1204 memset(buf,0,sizeof(struct _stat));
1206 /* FIXME: rdev isn't drive num, despite what the docs says-what is it? */
1207 if (MSVCRT_iswalpha(*path))
1208 buf->st_dev = buf->st_rdev = toupperW(*path - (WCHAR)L'A'); /* drive num */
1210 buf->st_dev = buf->st_rdev = _getdrive() - 1;
1212 plen = strlenW(path);
1214 /* Dir, or regular file? */
1215 if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1216 (path[plen-1] == (WCHAR)L'\\'))
1217 mode |= (_S_IFDIR | MSVCRT_S_IEXEC);
1222 if (plen > 6 && path[plen-4] == (WCHAR)L'.') /* shortest exe: "\x.exe" */
1224 ULONGLONG ext = tolowerW(path[plen-1]) | (tolowerW(path[plen-2]) << 16) |
1225 ((ULONGLONG)tolowerW(path[plen-3]) << 32);
1226 if (ext == WCEXE || ext == WCBAT || ext == WCCMD || ext == WCCOM)
1227 mode |= MSVCRT_S_IEXEC;
1231 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1232 mode |= MSVCRT_S_IWRITE;
1234 buf->st_mode = mode;
1236 buf->st_size = hfi.nFileSizeLow;
1237 RtlTimeToSecondsSince1970(&hfi.ftLastAccessTime, &dw);
1239 RtlTimeToSecondsSince1970(&hfi.ftLastWriteTime, &dw);
1240 buf->st_mtime = buf->st_ctime = dw;
1241 TRACE("\n%d %d %d %ld %ld %ld\n", buf->st_mode,buf->st_nlink,buf->st_size,
1242 buf->st_atime,buf->st_mtime, buf->st_ctime);
1246 /*********************************************************************
1251 return _lseek(fd, 0, SEEK_CUR);
1254 /*********************************************************************
1255 * _tempnam (MSVCRT.@)
1257 char *_tempnam(const char *dir, const char *prefix)
1259 char tmpbuf[MAX_PATH];
1261 TRACE("dir (%s) prefix (%s)\n",dir,prefix);
1262 if (GetTempFileNameA(dir,prefix,0,tmpbuf))
1264 TRACE("got name (%s)\n",tmpbuf);
1265 return _strdup(tmpbuf);
1267 TRACE("failed (%ld)\n",GetLastError());
1271 /*********************************************************************
1272 * _wtempnam (MSVCRT.@)
1274 WCHAR *_wtempnam(const WCHAR *dir, const WCHAR *prefix)
1276 WCHAR tmpbuf[MAX_PATH];
1278 TRACE("dir (%s) prefix (%s)\n",debugstr_w(dir),debugstr_w(prefix));
1279 if (GetTempFileNameW(dir,prefix,0,tmpbuf))
1281 TRACE("got name (%s)\n",debugstr_w(tmpbuf));
1282 return _wcsdup(tmpbuf);
1284 TRACE("failed (%ld)\n",GetLastError());
1288 /*********************************************************************
1291 int _umask(int umask)
1293 int old_umask = MSVCRT_umask;
1294 TRACE("(%d)\n",umask);
1295 MSVCRT_umask = umask;
1299 /*********************************************************************
1302 int _utime(const char* path, struct _utimbuf *t)
1304 int fd = _open(path, _O_WRONLY | _O_BINARY);
1308 int retVal = _futime(fd, t);
1315 /*********************************************************************
1316 * _wutime (MSVCRT.@)
1318 int _wutime(const WCHAR* path, struct _utimbuf *t)
1320 int fd = _wopen(path, _O_WRONLY | _O_BINARY);
1324 int retVal = _futime(fd, t);
1331 /*********************************************************************
1334 int _write(int fd, const void* buf, unsigned int count)
1337 HANDLE hand = msvcrt_fdtoh(fd);
1339 /* Dont trace small writes, it gets *very* annoying */
1341 // TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
1342 if (hand == INVALID_HANDLE_VALUE)
1345 /* If appending, go to EOF */
1346 if (MSVCRT_flags[fd] & MSVCRT__IOAPPEND)
1347 _lseek(fd, 0, FILE_END);
1349 if (WriteFile(hand, buf, count, &num_written, NULL)
1350 && (num_written == count))
1353 TRACE(":failed-last error (%ld)\n",GetLastError());
1354 if (MSVCRT_files[fd])
1355 MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
1360 /*********************************************************************
1363 int _putw(int val, MSVCRT_FILE* file)
1365 return _write(file->_file, &val, sizeof(val)) == 1? val : MSVCRT_EOF;
1368 /*********************************************************************
1369 * clearerr (MSVCRT.@)
1371 void MSVCRT_clearerr(MSVCRT_FILE* file)
1373 TRACE(":file (%p) fd (%d)\n",file,file->_file);
1374 file->_flag &= ~(MSVCRT__IOERR | MSVCRT__IOEOF);
1377 /*********************************************************************
1380 int MSVCRT_fclose(MSVCRT_FILE* file)
1383 r=_close(file->_file);
1384 return ((r==MSVCRT_EOF) || (file->_flag & MSVCRT__IOERR) ? MSVCRT_EOF : 0);
1387 /*********************************************************************
1390 int MSVCRT_feof(MSVCRT_FILE* file)
1392 return file->_flag & MSVCRT__IOEOF;
1395 /*********************************************************************
1398 int MSVCRT_ferror(MSVCRT_FILE* file)
1400 return file->_flag & MSVCRT__IOERR;
1403 /*********************************************************************
1406 int MSVCRT_fflush(MSVCRT_FILE* file)
1412 int res=msvcrt_flush_buffer(file);
1417 /*********************************************************************
1420 int MSVCRT_fgetc(MSVCRT_FILE* file)
1424 return *(unsigned char *)file->_ptr++;
1426 return _filbuf(file);
1430 /*********************************************************************
1431 * _fgetchar (MSVCRT.@)
1435 return MSVCRT_fgetc(MSVCRT_stdin);
1438 /*********************************************************************
1439 * _filbuf (MSVCRT.@)
1441 int _filbuf(MSVCRT_FILE* file)
1444 /* Allocate buffer if needed */
1445 if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF) ) {
1446 msvcrt_alloc_buffer(file);
1448 if(!(file->_flag & MSVCRT__IOREAD)) {
1449 if(file->_flag & MSVCRT__IORW) {
1450 file->_flag |= MSVCRT__IOREAD;
1455 if(file->_flag & MSVCRT__IONBF) {
1457 if (_read(file->_file,&c,1) != 1) {
1458 file->_flag |= MSVCRT__IOEOF;
1463 file->_cnt = _read(file->_file, file->_base, file->_bufsiz);
1464 if(file->_cnt<0) file->_cnt = 0;
1466 file->_flag |= MSVCRT__IOEOF;
1470 file->_ptr = file->_base+1;
1471 return *(unsigned char *)file->_base;
1475 /*********************************************************************
1476 * fgetpos (MSVCRT.@)
1478 int MSVCRT_fgetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
1480 *pos = MSVCRT_ftell(file);
1481 return (*pos == -1? -1 : 0);
1484 /*********************************************************************
1487 char *MSVCRT_fgets(char *s, int size, MSVCRT_FILE* file)
1490 char * buf_start = s;
1492 TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
1493 file,file->_file,s,size);
1495 for(cc = MSVCRT_fgetc(file); cc != MSVCRT_EOF && cc != '\n';
1496 cc = MSVCRT_fgetc(file))
1499 if (--size <= 0) break;
1502 if ((cc == MSVCRT_EOF) && (s == buf_start)) /* If nothing read, return 0*/
1504 TRACE(":nothing read\n");
1511 TRACE(":got '%s'\n", buf_start);
1515 /*********************************************************************
1518 MSVCRT_wint_t MSVCRT_fgetwc(MSVCRT_FILE* file)
1521 if (_read(file->_file, &wc, sizeof(wc)) != sizeof(wc))
1526 /*********************************************************************
1529 MSVCRT_wint_t MSVCRT_getwc(MSVCRT_FILE* file)
1531 return MSVCRT_fgetwc(file);
1534 /*********************************************************************
1535 * _fgetwchar (MSVCRT.@)
1537 MSVCRT_wint_t _fgetwchar(void)
1539 return MSVCRT_fgetwc(MSVCRT_stdin);
1542 /*********************************************************************
1543 * getwchar (MSVCRT.@)
1545 MSVCRT_wint_t MSVCRT_getwchar(void)
1547 return _fgetwchar();
1550 /*********************************************************************
1553 WCHAR *MSVCRT_fgetws(WCHAR *s, int size, MSVCRT_FILE* file)
1556 WCHAR * buf_start = s;
1558 TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
1559 file,file->_file,s,size);
1561 for(cc = MSVCRT_fgetwc(file); cc != MSVCRT_WEOF && cc != L'\n';
1562 cc = MSVCRT_fgetwc(file))
1565 if (--size <= 0) break;
1568 if ((cc == MSVCRT_EOF) && (s == buf_start)) /* If nothing read, return 0*/
1570 TRACE(":nothing read\n");
1577 /* TRACE(":got '%s'\n", buf_start); */
1582 /*********************************************************************
1585 MSVCRT_wint_t MSVCRT_fputwc(MSVCRT_wint_t wc, MSVCRT_FILE* file)
1588 if (MSVCRT_fwrite( &mwc, sizeof(mwc), 1, file) != 1)
1593 /*********************************************************************
1594 * _fputwchar (MSVCRT.@)
1596 MSVCRT_wint_t _fputwchar(MSVCRT_wint_t wc)
1598 return MSVCRT_fputwc(wc, MSVCRT_stdout);
1601 /*********************************************************************
1604 MSVCRT_FILE* MSVCRT_fopen(const char *path, const char *mode)
1607 int flags = 0, plus = 0, fd;
1608 const char* search = mode;
1610 TRACE("(%s,%s)\n",path,mode);
1613 if (*search++ == '+')
1616 /* map mode string to open() flags. "man fopen" for possibilities. */
1620 flags = (plus ? _O_RDWR : _O_RDONLY);
1623 flags = _O_CREAT | _O_TRUNC | (plus ? _O_RDWR : _O_WRONLY);
1626 flags = _O_CREAT | _O_APPEND | (plus ? _O_RDWR : _O_WRONLY);
1641 flags &= ~_O_BINARY;
1646 FIXME(":unknown flag %c not supported\n",mode[-1]);
1649 fd = _open(path, flags);
1654 file = msvcrt_alloc_fp(fd);
1655 TRACE(":got (%p)\n",file);
1662 /*********************************************************************
1663 * _wfopen (MSVCRT.@)
1665 MSVCRT_FILE *_wfopen(const WCHAR *path, const WCHAR *mode)
1667 const unsigned int plen = strlenW(path), mlen = strlenW(mode);
1668 char *patha = MSVCRT_calloc(plen + 1, 1);
1669 char *modea = MSVCRT_calloc(mlen + 1, 1);
1671 TRACE("(%s,%s)\n",debugstr_w(path),debugstr_w(mode));
1673 if (patha && modea &&
1674 WideCharToMultiByte(CP_ACP,0,path,plen,patha,plen,NULL,NULL) &&
1675 WideCharToMultiByte(CP_ACP,0,mode,mlen,modea,mlen,NULL,NULL))
1677 MSVCRT_FILE *retval = MSVCRT_fopen(patha,modea);
1683 MSVCRT__set_errno(GetLastError());
1687 /*********************************************************************
1688 * _fsopen (MSVCRT.@)
1690 MSVCRT_FILE* _fsopen(const char *path, const char *mode, int share)
1692 FIXME(":(%s,%s,%d),ignoring share mode!\n",path,mode,share);
1693 return MSVCRT_fopen(path,mode);
1696 /*********************************************************************
1697 * _wfsopen (MSVCRT.@)
1699 MSVCRT_FILE* _wfsopen(const WCHAR *path, const WCHAR *mode, int share)
1701 FIXME(":(%s,%s,%d),ignoring share mode!\n",
1702 debugstr_w(path),debugstr_w(mode),share);
1703 return _wfopen(path,mode);
1706 /*********************************************************************
1709 int MSVCRT_fputc(int c, MSVCRT_FILE* file)
1716 return _flsbuf(c, file);
1720 /*********************************************************************
1721 * _flsbuf (MSVCRT.@)
1723 int _flsbuf(int c, MSVCRT_FILE* file)
1725 /* Flush output buffer */
1726 if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
1727 msvcrt_alloc_buffer(file);
1729 if(!(file->_flag & MSVCRT__IOWRT)) {
1730 if(file->_flag & MSVCRT__IORW) {
1731 file->_flag |= MSVCRT__IOWRT;
1737 int res=msvcrt_flush_buffer(file);
1738 return res?res : MSVCRT_fputc(c, file);
1741 return _write(file->_file, &cc, 1) == 1? c : MSVCRT_EOF;
1745 /*********************************************************************
1746 * _fputchar (MSVCRT.@)
1748 int _fputchar(int c)
1750 return MSVCRT_fputc(c, MSVCRT_stdout);
1753 /*********************************************************************
1756 MSVCRT_size_t MSVCRT_fread(void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
1757 { MSVCRT_size_t rcnt=size * nmemb;
1758 MSVCRT_size_t read=0;
1760 /* first buffered data */
1762 int pcnt= (rcnt>file->_cnt)? file->_cnt:rcnt;
1763 memcpy(ptr, file->_ptr, pcnt);
1769 } else if(!(file->_flag & MSVCRT__IOREAD )) {
1770 if(file->_flag & MSVCRT__IORW) {
1771 file->_flag |= MSVCRT__IOREAD;
1775 if(rcnt) pread = _read(file->_file,ptr, rcnt);
1782 /*********************************************************************
1783 * freopen (MSVCRT.@)
1786 MSVCRT_FILE* MSVCRT_freopen(const char *path, const char *mode,MSVCRT_FILE* file)
1788 MSVCRT_FILE* newfile;
1791 TRACE(":path (%p) mode (%s) file (%p) fd (%d)\n",path,mode,file,file->_file);
1792 if (!file || ((fd = file->_file) < 0) || fd > MSVCRT_fdend)
1798 FIXME(":reopen on user file not implemented!\n");
1799 MSVCRT__set_errno(ERROR_CALL_NOT_IMPLEMENTED);
1802 if(MSVCRT_fclose(file))
1804 return MSVCRT_fopen(path, mode);
1807 /* first, create the new file */
1808 if ((newfile = MSVCRT_fopen(path,mode)) == NULL)
1811 if (fd < 3 && SetStdHandle(fd == 0 ? STD_INPUT_HANDLE :
1812 (fd == 1? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE),
1813 MSVCRT_handles[newfile->_file]))
1815 /* Redirecting std handle to file , copy over.. */
1816 MSVCRT_handles[fd] = MSVCRT_handles[newfile->_file];
1817 MSVCRT_flags[fd] = MSVCRT_flags[newfile->_file];
1818 memcpy(&MSVCRT__iob[fd], newfile, sizeof (MSVCRT_FILE));
1819 MSVCRT__iob[fd]._file = fd;
1820 /* And free up the resources allocated by fopen, but
1821 * not the HANDLE we copied. */
1822 MSVCRT_free(MSVCRT_files[fd]);
1823 msvcrt_free_fd(newfile->_file);
1824 return &MSVCRT__iob[fd];
1827 WARN(":failed-last error (%ld)\n",GetLastError());
1828 MSVCRT_fclose(newfile);
1829 MSVCRT__set_errno(GetLastError());
1833 /*********************************************************************
1834 * fsetpos (MSVCRT.@)
1836 int MSVCRT_fsetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
1838 return _lseek(file->_file,*pos,SEEK_SET);
1841 /* helper function for fscanf. Returns the value of character c in the
1842 * given base, or -1 if the given character is not a digit of the base.
1844 static int char2digit(char c, int base) {
1845 if ((c>='0') && (c<='9') && (c<='0'+base-1)) return (c-'0');
1846 if (base<=10) return -1;
1847 if ((c>='A') && (c<='Z') && (c<='A'+base-11)) return (c-'A'+10);
1848 if ((c>='a') && (c<='z') && (c<='a'+base-11)) return (c-'a'+10);
1852 /*********************************************************************
1854 * Implemented based on
1855 * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/html/_crt_format_specification_fields_.2d_.scanf_and_wscanf_functions.asp
1856 * Extended by C. Scott Ananian <cananian@alumni.princeton.edu> to handle
1857 * more types of format spec.
1859 int MSVCRT_fscanf(MSVCRT_FILE* file, const char *format, ...)
1861 /* NOTE: If you extend this function, extend MSVCRT__cscanf in console.c too */
1865 if (!*format) return 0;
1866 WARN("%p (\"%s\"): semi-stub\n", file, format);
1867 nch = MSVCRT_fgetc(file);
1868 va_start(ap, format);
1870 /* a whitespace character in the format string causes scanf to read,
1871 * but not store, all consecutive white-space characters in the input
1872 * up to the next non-white-space character. One white space character
1873 * in the input matches any number (including zero) and combination of
1874 * white-space characters in the input. */
1875 if (isspace(*format)) {
1876 /* skip whitespace */
1877 while ((nch!=MSVCRT_EOF) && isspace(nch))
1878 nch = MSVCRT_fgetc(file);
1880 /* a format specification causes scanf to read and convert characters
1881 * in the input into values of a specified type. The value is assigned
1882 * to an argument in the argument list. Format specifications have
1883 * the form %[*][width][{h | l | I64 | L}]type */
1884 /* FIXME: unimplemented: h/l/I64/L modifiers and some type specs. */
1885 else if (*format == '%') {
1886 int st = 0; int suppress = 0; int width = 0;
1887 int base, number_signed;
1889 /* look for leading asterisk, which means 'suppress assignment of
1895 /* look for width specification */
1896 while (isdigit(*format)) {
1898 width+=*format++ - '0';
1900 if (width==0) width=-1; /* no width spec seen */
1902 case '%': /* read a percent symbol */
1903 if (nch!='%') break;
1904 nch = MSVCRT_fgetc(file);
1907 case 'X': /* hexadecimal integer. */
1908 base = 16; number_signed = 0;
1910 case 'o': /* octal integer */
1911 base = 8; number_signed = 0;
1913 case 'u': /* unsigned decimal integer */
1914 base = 10; number_signed = 0;
1916 case 'd': /* signed decimal integer */
1917 base = 10; number_signed = 1;
1919 case 'i': /* generic integer */
1920 base = 0; number_signed = 1;
1922 /* read an integer */
1923 int*val = suppress ? NULL : va_arg(ap, int*);
1924 int cur = 0; int negative = 0; int seendigit=0;
1925 /* skip initial whitespace */
1926 while ((nch!=MSVCRT_EOF) && isspace(nch))
1927 nch = MSVCRT_fgetc(file);
1929 if (number_signed && (nch == '-' || nch == '+')) {
1930 negative = (nch=='-');
1931 nch = MSVCRT_fgetc(file);
1932 if (width>0) width--;
1934 /* look for leading indication of base */
1935 if (width!=0 && nch == '0') {
1936 nch = MSVCRT_fgetc(file);
1937 if (width>0) width--;
1939 if (width!=0 && (nch=='x' || nch=='X')) {
1943 nch = MSVCRT_fgetc(file);
1944 if (width>0) width--;
1952 /* throw away leading zeros */
1953 while (width!=0 && nch=='0') {
1954 nch = MSVCRT_fgetc(file);
1955 if (width>0) width--;
1958 /* get first digit. Keep working copy negative, as the
1959 * range of negative numbers in two's complement notation
1960 * is one larger than the range of positive numbers. */
1961 if (width!=0 && char2digit(nch, base)!=-1) {
1962 cur = -char2digit(nch, base);
1963 nch = MSVCRT_fgetc(file);
1964 if (width>0) width--;
1967 /* read until no more digits */
1968 while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
1969 cur = cur*base + char2digit(nch, base);
1970 nch = MSVCRT_fgetc(file);
1971 if (width>0) width--;
1974 /* negate parsed number if non-negative */
1975 if (!negative) cur=-cur;
1977 if (!seendigit) break; /* not a valid number */
1979 if (!suppress) *val = cur;
1986 case 'G': { /* read a float */
1987 float*val = suppress ? NULL : va_arg(ap, float*);
1990 /* skip initial whitespace */
1991 while ((nch!=MSVCRT_EOF) && isspace(nch))
1992 nch = MSVCRT_fgetc(file);
1994 if (nch == '-' || nch == '+') {
1995 negative = (nch=='-');
1996 if (width>0) width--;
1997 if (width==0) break;
1998 nch = MSVCRT_fgetc(file);
2000 /* get first digit. */
2001 if (!isdigit(nch)) break;
2002 cur = (nch - '0') * (negative ? -1 : 1);
2003 nch = MSVCRT_fgetc(file);
2004 if (width>0) width--;
2005 /* read until no more digits */
2006 while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
2007 cur = cur*10 + (nch - '0');
2008 nch = MSVCRT_fgetc(file);
2009 if (width>0) width--;
2011 /* handle decimals */
2012 if (width!=0 && nch == '.') {
2014 nch = MSVCRT_fgetc(file);
2015 if (width>0) width--;
2016 while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
2018 cur += dec * (nch - '0');
2019 nch = MSVCRT_fgetc(file);
2020 if (width>0) width--;
2023 /* handle exponent */
2024 if (width!=0 && (nch == 'e' || nch == 'E')) {
2025 int exponent = 0, negexp = 0;
2027 nch = MSVCRT_fgetc(file);
2028 if (width>0) width--;
2029 /* possible sign on the exponent */
2030 if (width!=0 && (nch=='+' || nch=='-')) {
2031 negexp = (nch=='-');
2032 nch = MSVCRT_fgetc(file);
2033 if (width>0) width--;
2035 /* exponent digits */
2036 while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
2038 exponent += (nch - '0');
2039 nch = MSVCRT_fgetc(file);
2040 if (width>0) width--;
2042 /* update 'cur' with this exponent. */
2043 expcnt = negexp ? .1 : 10;
2044 while (exponent!=0) {
2048 expcnt=expcnt*expcnt;
2052 if (!suppress) *val = cur;
2055 case 's': { /* read a word */
2056 char*str = suppress ? NULL : va_arg(ap, char*);
2058 /* skip initial whitespace */
2059 while ((nch!=MSVCRT_EOF) && isspace(nch))
2060 nch = MSVCRT_fgetc(file);
2061 /* read until whitespace */
2062 while (width!=0 && (nch!=MSVCRT_EOF) && !isspace(nch)) {
2063 if (!suppress) *sptr++ = nch;
2065 nch = MSVCRT_fgetc(file);
2066 if (width>0) width--;
2069 if (!suppress) *sptr = 0;
2070 TRACE("read word: %s\n", str);
2073 default: FIXME("unhandled: %%%c\n", *format);
2074 /* From spec: "if a percent sign is followed by a character
2075 * that has no meaning as a format-control character, that
2076 * character and the following characters are treated as
2077 * an ordinary sequence of characters, that is, a sequence
2078 * of characters that must match the input. For example,
2079 * to specify that a percent-sign character is to be input,
2081 * LEAVING AS-IS because we catch bugs better that way. */
2083 if (st && !suppress) rd++;
2086 /* a non-white-space character causes scanf to read, but not store,
2087 * a matching non-white-space character. */
2089 /* check for character match */
2091 nch = MSVCRT_fgetc(file);
2096 if (nch!=MSVCRT_EOF) {
2097 FIXME("need ungetch\n");
2100 TRACE("returning %d\n", rd);
2104 /*********************************************************************
2107 int MSVCRT_fseek(MSVCRT_FILE* file, long offset, int whence)
2109 /* Flush output if needed */
2110 if(file->_flag & MSVCRT__IOWRT)
2111 msvcrt_flush_buffer(file);
2113 if(whence == SEEK_CUR && file->_flag & MSVCRT__IOREAD ) {
2114 offset -= file->_cnt;
2116 /* Discard buffered input */
2118 file->_ptr = file->_base;
2119 /* Reset direction of i/o */
2120 if(file->_flag & MSVCRT__IORW) {
2121 file->_flag &= ~(MSVCRT__IOREAD|MSVCRT__IOWRT);
2123 return _lseek(file->_file,offset,whence);
2126 /*********************************************************************
2129 LONG MSVCRT_ftell(MSVCRT_FILE* file)
2134 if( file->_flag & MSVCRT__IOWRT ) {
2135 off = file->_ptr - file->_base;
2140 pos = _tell(file->_file);
2141 if(pos == -1) return pos;
2145 /*********************************************************************
2148 MSVCRT_size_t MSVCRT_fwrite(const void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
2150 MSVCRT_size_t wrcnt=size * nmemb;
2155 int pcnt=(file->_cnt>wrcnt)? wrcnt: file->_cnt;
2156 memcpy(file->_ptr, ptr, pcnt);
2162 } else if(!(file->_flag & MSVCRT__IOWRT)) {
2163 if(file->_flag & MSVCRT__IORW) {
2164 file->_flag |= MSVCRT__IOWRT;
2170 int res=msvcrt_flush_buffer(file);
2172 int pwritten = _write(file->_file, ptr, wrcnt);
2173 if (pwritten <= 0) pwritten=0;
2174 written += pwritten;
2177 return written / size;
2180 /*********************************************************************
2183 int MSVCRT_fputs(const char *s, MSVCRT_FILE* file)
2185 size_t len = strlen(s);
2186 return MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
2189 /*********************************************************************
2192 int MSVCRT_fputws(const WCHAR *s, MSVCRT_FILE* file)
2194 size_t len = strlenW(s);
2195 return MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
2198 /*********************************************************************
2199 * getchar (MSVCRT.@)
2201 int MSVCRT_getchar(void)
2203 return MSVCRT_fgetc(MSVCRT_stdin);
2206 /*********************************************************************
2209 int MSVCRT_getc(MSVCRT_FILE* file)
2211 return MSVCRT_fgetc(file);
2214 /*********************************************************************
2217 char *MSVCRT_gets(char *buf)
2220 char * buf_start = buf;
2222 for(cc = MSVCRT_fgetc(MSVCRT_stdin); cc != MSVCRT_EOF && cc != '\n';
2223 cc = MSVCRT_fgetc(MSVCRT_stdin))
2224 if(cc != '\r') *buf++ = (char)cc;
2228 TRACE("got '%s'\n", buf_start);
2232 /*********************************************************************
2235 int MSVCRT_putc(int c, MSVCRT_FILE* file)
2237 return MSVCRT_fputc(c, file);
2240 /*********************************************************************
2241 * putchar (MSVCRT.@)
2243 int MSVCRT_putchar(int c)
2245 return MSVCRT_fputc(c, MSVCRT_stdout);
2248 /*********************************************************************
2251 int MSVCRT_puts(const char *s)
2253 size_t len = strlen(s);
2254 if (MSVCRT_fwrite(s,sizeof(*s),len,MSVCRT_stdout) != len) return MSVCRT_EOF;
2255 return MSVCRT_fwrite("\n",1,1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
2258 /*********************************************************************
2261 int _putws(const WCHAR *s)
2263 static const WCHAR nl = '\n';
2264 size_t len = strlenW(s);
2265 if (MSVCRT_fwrite(s,sizeof(*s),len,MSVCRT_stdout) != len) return MSVCRT_EOF;
2266 return MSVCRT_fwrite(&nl,sizeof(nl),1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
2269 /*********************************************************************
2272 int MSVCRT_remove(const char *path)
2274 TRACE("(%s)\n",path);
2275 if (DeleteFileA(path))
2277 TRACE(":failed (%ld)\n",GetLastError());
2278 MSVCRT__set_errno(GetLastError());
2282 /*********************************************************************
2283 * _wremove (MSVCRT.@)
2285 int _wremove(const WCHAR *path)
2287 TRACE("(%s)\n",debugstr_w(path));
2288 if (DeleteFileW(path))
2290 TRACE(":failed (%ld)\n",GetLastError());
2291 MSVCRT__set_errno(GetLastError());
2295 /*********************************************************************
2298 int MSVCRT_scanf(const char *format, ...)
2303 va_start(valist, format);
2304 res = MSVCRT_fscanf(MSVCRT_stdin, format, valist);
2309 /*********************************************************************
2312 int MSVCRT_rename(const char *oldpath,const char *newpath)
2314 TRACE(":from %s to %s\n",oldpath,newpath);
2315 if (MoveFileExA(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
2317 TRACE(":failed (%ld)\n",GetLastError());
2318 MSVCRT__set_errno(GetLastError());
2322 /*********************************************************************
2323 * _wrename (MSVCRT.@)
2325 int _wrename(const WCHAR *oldpath,const WCHAR *newpath)
2327 TRACE(":from %s to %s\n",debugstr_w(oldpath),debugstr_w(newpath));
2328 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
2330 TRACE(":failed (%ld)\n",GetLastError());
2331 MSVCRT__set_errno(GetLastError());
2335 /*********************************************************************
2336 * setvbuf (MSVCRT.@)
2338 int MSVCRT_setvbuf(MSVCRT_FILE* file, char *buf, int mode, MSVCRT_size_t size)
2340 /* TODO: Check if file busy */
2342 MSVCRT_free(file->_base);
2346 if(mode == MSVCRT__IOFBF) {
2347 file->_flag &= ~MSVCRT__IONBF;
2348 file->_base = file->_ptr = buf;
2350 file->_bufsiz = size;
2353 file->_flag |= MSVCRT__IONBF;
2358 /*********************************************************************
2361 void MSVCRT_setbuf(MSVCRT_FILE* file, char *buf)
2363 MSVCRT_setvbuf(file, buf, buf ? MSVCRT__IOFBF : MSVCRT__IONBF, MSVCRT_BUFSIZ);
2366 /*********************************************************************
2369 char *MSVCRT_tmpnam(char *s)
2371 char tmpbuf[MAX_PATH];
2372 char* prefix = "TMP";
2373 if (!GetTempPathA(MAX_PATH,tmpbuf) ||
2374 !GetTempFileNameA(tmpbuf,prefix,0,MSVCRT_tmpname))
2376 TRACE(":failed-last error (%ld)\n",GetLastError());
2379 TRACE(":got tmpnam %s\n",MSVCRT_tmpname);
2384 /*********************************************************************
2385 * tmpfile (MSVCRT.@)
2387 MSVCRT_FILE* MSVCRT_tmpfile(void)
2389 char *filename = MSVCRT_tmpnam(NULL);
2391 fd = _open(filename, _O_CREAT | _O_BINARY | _O_RDWR | _O_TEMPORARY);
2393 return msvcrt_alloc_fp(fd);
2397 /*********************************************************************
2398 * vfprintf (MSVCRT.@)
2400 int MSVCRT_vfprintf(MSVCRT_FILE* file, const char *format, va_list valist)
2402 char buf[2048], *mem = buf;
2403 int written, resize = sizeof(buf), retval;
2404 /* There are two conventions for vsnprintf failing:
2405 * Return -1 if we truncated, or
2406 * Return the number of bytes that would have been written
2407 * The code below handles both cases
2409 while ((written = vsnprintf(mem, resize, format, valist)) == -1 ||
2412 resize = (written == -1 ? resize * 2 : written + 1);
2415 if (!(mem = (char *)MSVCRT_malloc(resize)))
2418 retval = MSVCRT_fwrite(mem, sizeof(*mem), written, file);
2424 /*********************************************************************
2425 * vfwprintf (MSVCRT.@)
2427 * Is final char included in written (then resize is too big) or not
2428 * (then we must test for equality too)?
2430 int MSVCRT_vfwprintf(MSVCRT_FILE* file, const WCHAR *format, va_list valist)
2432 WCHAR buf[2048], *mem = buf;
2433 int written, resize = sizeof(buf) / sizeof(WCHAR), retval;
2434 /* See vfprintf comments */
2435 while ((written = _vsnwprintf(mem, resize, format, valist)) == -1 ||
2438 resize = (written == -1 ? resize * 2 : written + sizeof(WCHAR));
2441 if (!(mem = (WCHAR *)MSVCRT_malloc(resize*sizeof(*mem))))
2444 retval = MSVCRT_fwrite(mem, sizeof(*mem), written, file);
2450 /*********************************************************************
2451 * vprintf (MSVCRT.@)
2453 int MSVCRT_vprintf(const char *format, va_list valist)
2455 return MSVCRT_vfprintf(MSVCRT_stdout,format,valist);
2458 /*********************************************************************
2459 * vwprintf (MSVCRT.@)
2461 int MSVCRT_vwprintf(const WCHAR *format, va_list valist)
2463 return MSVCRT_vfwprintf(MSVCRT_stdout,format,valist);
2466 /*********************************************************************
2467 * fprintf (MSVCRT.@)
2469 int MSVCRT_fprintf(MSVCRT_FILE* file, const char *format, ...)
2473 va_start(valist, format);
2474 res = MSVCRT_vfprintf(file, format, valist);
2479 /*********************************************************************
2480 * fwprintf (MSVCRT.@)
2482 int MSVCRT_fwprintf(MSVCRT_FILE* file, const WCHAR *format, ...)
2486 va_start(valist, format);
2487 res = MSVCRT_vfwprintf(file, format, valist);
2492 /*********************************************************************
2495 int MSVCRT_printf(const char *format, ...)
2499 va_start(valist, format);
2500 res = MSVCRT_vfprintf(MSVCRT_stdout, format, valist);
2505 /*********************************************************************
2508 int MSVCRT_ungetc(int c, MSVCRT_FILE * file)
2510 if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
2511 msvcrt_alloc_buffer(file);
2514 if(file->_ptr>file->_base) {
2523 /*********************************************************************
2524 * ungetwc (MSVCRT.@)
2526 MSVCRT_wint_t MSVCRT_ungetwc(MSVCRT_wint_t wc, MSVCRT_FILE * file)
2529 char * pp = (char *)&mwc;
2531 for(i=sizeof(WCHAR)-1;i>=0;i--) {
2532 if(pp[i] != MSVCRT_ungetc(pp[i],file))
2538 /*********************************************************************
2539 * wprintf (MSVCRT.@)
2541 int MSVCRT_wprintf(const WCHAR *format, ...)
2545 va_start(valist, format);
2546 res = MSVCRT_vwprintf(format, valist);