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
25 #include "wine/port.h"
35 #include "wine/unicode.h"
36 #include "msvcrt/direct.h"
37 #include "msvcrt/fcntl.h"
38 #include "msvcrt/io.h"
39 #include "msvcrt/sys/locking.h"
40 #include "msvcrt/stdio.h"
41 #include "msvcrt/stdlib.h"
42 #include "msvcrt/string.h"
43 #include "msvcrt/sys/stat.h"
44 #include "msvcrt/sys/utime.h"
45 #include "msvcrt/time.h"
46 #include "msvcrt/share.h"
48 #include "wine/debug.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
52 /* for stat mode, permissions apply to all,owner and group */
53 #define MSVCRT_S_IREAD (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6))
54 #define MSVCRT_S_IWRITE (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6))
55 #define MSVCRT_S_IEXEC (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6))
57 /* _access() bit flags FIXME: incomplete */
58 #define MSVCRT_W_OK 0x02
61 /* FIXME: Make this dynamic */
62 #define MSVCRT_MAX_FILES 257
64 HANDLE MSVCRT_handles[MSVCRT_MAX_FILES];
65 MSVCRT_FILE* MSVCRT_files[MSVCRT_MAX_FILES];
66 int MSVCRT_flags[MSVCRT_MAX_FILES];
67 char *MSVCRT_tempfiles[MSVCRT_MAX_FILES];
68 MSVCRT_FILE MSVCRT__iob[3];
69 #define MSVCRT_stdin (MSVCRT__iob+STDIN_FILENO)
70 #define MSVCRT_stdout (MSVCRT__iob+STDOUT_FILENO)
71 #define MSVCRT_stderr (MSVCRT__iob+STDERR_FILENO)
73 static int MSVCRT_fdstart = 3; /* first unallocated fd */
74 static int MSVCRT_fdend = 3; /* highest allocated fd */
76 /* INTERNAL: process umask */
77 static int MSVCRT_umask = 0;
79 /* INTERNAL: Static buffer for temp file name */
80 static char MSVCRT_tmpname[MAX_PATH];
82 static const unsigned int EXE = 'e' << 16 | 'x' << 8 | 'e';
83 static const unsigned int BAT = 'b' << 16 | 'a' << 8 | 't';
84 static const unsigned int CMD = 'c' << 16 | 'm' << 8 | 'd';
85 static const unsigned int COM = 'c' << 16 | 'o' << 8 | 'm';
87 #define TOUL(x) (ULONGLONG)((WCHAR)L##x)
88 static const ULONGLONG WCEXE = TOUL('e') << 32 | TOUL('x') << 16 | TOUL('e');
89 static const ULONGLONG WCBAT = TOUL('b') << 32 | TOUL('a') << 16 | TOUL('t');
90 static const ULONGLONG WCCMD = TOUL('c') << 32 | TOUL('m') << 16 | TOUL('d');
91 static const ULONGLONG WCCOM = TOUL('c') << 32 | TOUL('o') << 16 | TOUL('m');
93 extern CRITICAL_SECTION MSVCRT_file_cs;
94 #define LOCK_FILES EnterCriticalSection(&MSVCRT_file_cs)
95 #define UNLOCK_FILES LeaveCriticalSection(&MSVCRT_file_cs)
98 /* INTERNAL: Get the HANDLE for a fd */
99 static HANDLE msvcrt_fdtoh(int fd)
101 if (fd < 0 || fd >= MSVCRT_fdend ||
102 MSVCRT_handles[fd] == INVALID_HANDLE_VALUE)
104 WARN(":fd (%d) - no handle!\n",fd);
106 *MSVCRT__errno() = MSVCRT_EBADF;
107 return INVALID_HANDLE_VALUE;
109 return MSVCRT_handles[fd];
112 /* INTERNAL: free a file entry fd */
113 static void msvcrt_free_fd(int fd)
115 MSVCRT_handles[fd] = INVALID_HANDLE_VALUE;
116 MSVCRT_files[fd] = 0;
117 MSVCRT_flags[fd] = 0;
118 TRACE(":fd (%d) freed\n",fd);
120 return; /* dont use 0,1,2 for user files */
121 if (fd == MSVCRT_fdend - 1)
123 if (fd < MSVCRT_fdstart)
127 /* INTERNAL: Allocate an fd slot from a Win32 HANDLE */
128 static int msvcrt_alloc_fd(HANDLE hand, int flag)
130 int fd = MSVCRT_fdstart;
132 TRACE(":handle (%d) allocating fd (%d)\n",hand,fd);
133 if (fd >= MSVCRT_MAX_FILES)
135 WARN(":files exhausted!\n");
138 MSVCRT_handles[fd] = hand;
139 MSVCRT_flags[fd] = flag;
141 /* locate next free slot */
142 if (fd == MSVCRT_fdend)
143 MSVCRT_fdstart = ++MSVCRT_fdend;
145 while(MSVCRT_fdstart < MSVCRT_fdend &&
146 MSVCRT_handles[MSVCRT_fdstart] != INVALID_HANDLE_VALUE)
152 /* INTERNAL: Allocate a FILE* for an fd slot
153 * This is done lazily to avoid memory wastage for low level open/write
154 * usage when a FILE* is not requested (but may be later).
156 static MSVCRT_FILE* msvcrt_alloc_fp(int fd)
158 TRACE(":fd (%d) allocating FILE*\n",fd);
159 if (fd < 0 || fd >= MSVCRT_fdend ||
160 MSVCRT_handles[fd] == INVALID_HANDLE_VALUE)
162 WARN(":invalid fd %d\n",fd);
164 *MSVCRT__errno() = MSVCRT_EBADF;
167 if (!MSVCRT_files[fd])
169 if ((MSVCRT_files[fd] = MSVCRT_calloc(sizeof(MSVCRT_FILE),1)))
171 MSVCRT_files[fd]->_file = fd;
172 MSVCRT_files[fd]->_flag = MSVCRT_flags[fd];
173 MSVCRT_files[fd]->_flag &= ~MSVCRT__IOAPPEND; /* mask out, see above */
176 TRACE(":got FILE* (%p)\n",MSVCRT_files[fd]);
177 return MSVCRT_files[fd];
181 /* INTERNAL: Set up stdin, stderr and stdout */
182 void msvcrt_init_io(void)
185 memset(MSVCRT__iob,0,3*sizeof(MSVCRT_FILE));
186 MSVCRT_handles[0] = GetStdHandle(STD_INPUT_HANDLE);
187 MSVCRT_flags[0] = MSVCRT__iob[0]._flag = MSVCRT__IOREAD;
188 MSVCRT_handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
189 MSVCRT_flags[1] = MSVCRT__iob[1]._flag = MSVCRT__IOWRT;
190 MSVCRT_handles[2] = GetStdHandle(STD_ERROR_HANDLE);
191 MSVCRT_flags[2] = MSVCRT__iob[2]._flag = MSVCRT__IOWRT;
193 TRACE(":handles (%d)(%d)(%d)\n",MSVCRT_handles[0],
194 MSVCRT_handles[1],MSVCRT_handles[2]);
196 for (i = 0; i < 3; i++)
198 /* FILE structs for stdin/out/err are static and never deleted */
199 MSVCRT_files[i] = &MSVCRT__iob[i];
200 MSVCRT__iob[i]._file = i;
201 MSVCRT_tempfiles[i] = NULL;
205 /* free everything on process exit */
206 void msvcrt_free_io(void)
214 /* INTERNAL: Flush stdio file buffer */
215 static int msvcrt_flush_buffer(MSVCRT_FILE* file)
218 int cnt=file->_ptr-file->_base;
219 if(cnt>0 && _write(file->_file, file->_base, cnt) != cnt) {
222 file->_ptr=file->_base;
223 file->_cnt=file->_bufsiz;
228 /* INTERNAL: Allocate stdio file buffer */
229 static void msvcrt_alloc_buffer(MSVCRT_FILE* file)
231 file->_base = MSVCRT_calloc(MSVCRT_BUFSIZ,1);
233 file->_bufsiz = MSVCRT_BUFSIZ;
234 file->_flag |= MSVCRT__IOMYBUF;
236 file->_base = (unsigned char *)(&file->_charbuf);
238 file->_bufsiz = sizeof(file->_charbuf);
240 file->_ptr = file->_base;
244 /*********************************************************************
247 MSVCRT_FILE *__p__iob(void)
249 return &MSVCRT__iob[0];
252 /*********************************************************************
255 int _access(const char *filename, int mode)
257 DWORD attr = GetFileAttributesA(filename);
259 TRACE("(%s,%d) %ld\n",filename,mode,attr);
261 if (!filename || attr == 0xffffffff)
263 MSVCRT__set_errno(GetLastError());
266 if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
268 MSVCRT__set_errno(ERROR_ACCESS_DENIED);
274 /*********************************************************************
275 * _waccess (MSVCRT.@)
277 int _waccess(const WCHAR *filename, int mode)
279 DWORD attr = GetFileAttributesW(filename);
281 TRACE("(%s,%d) %ld\n",debugstr_w(filename),mode,attr);
283 if (!filename || attr == 0xffffffff)
285 MSVCRT__set_errno(GetLastError());
288 if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
290 MSVCRT__set_errno(ERROR_ACCESS_DENIED);
296 /*********************************************************************
299 int _chmod(const char *path, int flags)
301 DWORD oldFlags = GetFileAttributesA(path);
303 if (oldFlags != 0x0FFFFFFFF)
305 DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
306 oldFlags | FILE_ATTRIBUTE_READONLY;
308 if (newFlags == oldFlags || SetFileAttributesA(path, newFlags))
311 MSVCRT__set_errno(GetLastError());
315 /*********************************************************************
318 int _wchmod(const WCHAR *path, int flags)
320 DWORD oldFlags = GetFileAttributesW(path);
322 if (oldFlags != 0x0FFFFFFFF)
324 DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
325 oldFlags | FILE_ATTRIBUTE_READONLY;
327 if (newFlags == oldFlags || SetFileAttributesW(path, newFlags))
330 MSVCRT__set_errno(GetLastError());
334 /*********************************************************************
337 int _unlink(const char *path)
339 TRACE("(%s)\n",path);
340 if(DeleteFileA(path))
342 TRACE("failed (%ld)\n",GetLastError());
343 MSVCRT__set_errno(GetLastError());
347 /*********************************************************************
348 * _wunlink (MSVCRT.@)
350 int _wunlink(const WCHAR *path)
352 TRACE("(%s)\n",debugstr_w(path));
353 if(DeleteFileW(path))
355 TRACE("failed (%ld)\n",GetLastError());
356 MSVCRT__set_errno(GetLastError());
360 /*********************************************************************
365 HANDLE hand = msvcrt_fdtoh(fd);
367 TRACE(":fd (%d) handle (%d)\n",fd,hand);
368 if (hand == INVALID_HANDLE_VALUE)
370 /* flush stdio buffers */
371 if(MSVCRT_files[fd]) {
372 if(MSVCRT_files[fd]->_flag & MSVCRT__IOWRT)
373 MSVCRT_fflush(MSVCRT_files[fd]);
375 if(MSVCRT_files[fd]->_flag & MSVCRT__IOMYBUF)
376 MSVCRT_free(MSVCRT_files[fd]->_base);
379 /* Dont free std FILE*'s, they are not dynamic */
380 if (fd > 2 && MSVCRT_files[fd])
381 MSVCRT_free(MSVCRT_files[fd]);
385 if (!CloseHandle(hand))
387 WARN(":failed-last error (%ld)\n",GetLastError());
388 MSVCRT__set_errno(GetLastError());
391 if (MSVCRT_tempfiles[fd])
393 TRACE("deleting temporary file '%s'\n",MSVCRT_tempfiles[fd]);
394 _unlink(MSVCRT_tempfiles[fd]);
395 MSVCRT_free(MSVCRT_tempfiles[fd]);
396 MSVCRT_tempfiles[fd] = NULL;
403 /*********************************************************************
408 HANDLE hand = msvcrt_fdtoh(fd);
410 TRACE(":fd (%d) handle (%d)\n",fd,hand);
411 if (hand == INVALID_HANDLE_VALUE)
414 if (!FlushFileBuffers(hand))
416 if (GetLastError() == ERROR_INVALID_HANDLE)
418 /* FlushFileBuffers fails for console handles
419 * so we ignore this error.
423 TRACE(":failed-last error (%ld)\n",GetLastError());
424 MSVCRT__set_errno(GetLastError());
431 /*********************************************************************
437 HANDLE hand = msvcrt_fdtoh(fd);
439 TRACE(":fd (%d) handle (%d)\n",fd,hand);
441 if (hand == INVALID_HANDLE_VALUE)
444 /* If we have a FILE* for this file, the EOF flag
445 * will be set by the read()/write() functions.
447 if (MSVCRT_files[fd])
448 return MSVCRT_flags[fd] & MSVCRT__IOEOF;
450 /* Otherwise we do it the hard way */
451 curpos = SetFilePointer(hand, 0, NULL, SEEK_CUR);
452 endpos = SetFilePointer(hand, 0, NULL, FILE_END);
454 if (curpos == endpos)
457 SetFilePointer(hand, curpos, 0, FILE_BEGIN);
461 /*********************************************************************
462 * _fcloseall (MSVCRT.@)
466 int num_closed = 0, i;
468 for (i = 3; i < MSVCRT_fdend; i++)
469 if (MSVCRT_handles[i] != INVALID_HANDLE_VALUE)
475 TRACE(":closed (%d) handles\n",num_closed);
479 /*********************************************************************
482 LONG _lseek(int fd, LONG offset, int whence)
485 HANDLE hand = msvcrt_fdtoh(fd);
487 TRACE(":fd (%d) handle (%d)\n",fd,hand);
488 if (hand == INVALID_HANDLE_VALUE)
491 if (whence < 0 || whence > 2)
493 *MSVCRT__errno() = MSVCRT_EINVAL;
497 TRACE(":fd (%d) to 0x%08lx pos %s\n",
498 fd,offset,(whence==SEEK_SET)?"SEEK_SET":
499 (whence==SEEK_CUR)?"SEEK_CUR":
500 (whence==SEEK_END)?"SEEK_END":"UNKNOWN");
502 if ((ret = SetFilePointer(hand, offset, NULL, whence)) != 0xffffffff)
504 if (MSVCRT_files[fd])
505 MSVCRT_files[fd]->_flag &= ~MSVCRT__IOEOF;
506 /* FIXME: What if we seek _to_ EOF - is EOF set? */
509 TRACE(":error-last error (%ld)\n",GetLastError());
510 if (MSVCRT_files[fd])
511 switch(GetLastError())
513 case ERROR_NEGATIVE_SEEK:
514 case ERROR_SEEK_ON_DEVICE:
515 MSVCRT__set_errno(GetLastError());
516 MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
524 /*********************************************************************
525 * _locking (MSVCRT.@)
527 * This is untested; the underlying LockFile doesn't work yet.
529 int _locking(int fd, int mode, LONG nbytes)
533 HANDLE hand = msvcrt_fdtoh(fd);
535 TRACE(":fd (%d) handle (%d)\n",fd,hand);
536 if (hand == INVALID_HANDLE_VALUE)
539 if (mode < 0 || mode > 4)
541 *MSVCRT__errno() = MSVCRT_EINVAL;
545 TRACE(":fd (%d) by 0x%08lx mode %s\n",
546 fd,nbytes,(mode==_LK_UNLCK)?"_LK_UNLCK":
547 (mode==_LK_LOCK)?"_LK_LOCK":
548 (mode==_LK_NBLCK)?"_LK_NBLCK":
549 (mode==_LK_RLCK)?"_LK_RLCK":
550 (mode==_LK_NBRLCK)?"_LK_NBRLCK":
553 if ((cur_locn = SetFilePointer(hand, 0L, NULL, SEEK_CUR)) == 0xffffffff)
555 FIXME ("Seek failed\n");
556 *MSVCRT__errno() = MSVCRT_EINVAL; /* FIXME */
559 if (mode == _LK_LOCK || mode == _LK_RLCK)
562 ret = 1; /* just to satisfy gcc */
565 ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
570 else if (mode == _LK_UNLCK)
571 ret = UnlockFile(hand, cur_locn, 0L, nbytes, 0L);
573 ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
574 /* FIXME - what about error settings? */
578 /*********************************************************************
581 void MSVCRT_rewind(MSVCRT_FILE* file)
583 TRACE(":file (%p) fd (%d)\n",file,file->_file);
584 MSVCRT_fseek(file, 0L, SEEK_SET);
585 MSVCRT_clearerr(file);
588 /*********************************************************************
591 MSVCRT_FILE* _fdopen(int fd, const char *mode)
593 MSVCRT_FILE* file = msvcrt_alloc_fp(fd);
595 TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,mode,file);
602 /*********************************************************************
603 * _wfdopen (MSVCRT.@)
605 MSVCRT_FILE* _wfdopen(int fd, const WCHAR *mode)
607 MSVCRT_FILE* file = msvcrt_alloc_fp(fd);
609 TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,debugstr_w(mode),file);
616 /*********************************************************************
617 * _filelength (MSVCRT.@)
619 LONG _filelength(int fd)
621 LONG curPos = _lseek(fd, 0, SEEK_CUR);
624 LONG endPos = _lseek(fd, 0, SEEK_END);
627 if (endPos != curPos)
628 _lseek(fd, curPos, SEEK_SET);
635 /*********************************************************************
638 int _fileno(MSVCRT_FILE* file)
640 TRACE(":FILE* (%p) fd (%d)\n",file,file->_file);
644 /*********************************************************************
645 * _flushall (MSVCRT.@)
649 int num_flushed = 0, i = 3;
651 while(i < MSVCRT_fdend)
652 if (MSVCRT_handles[i] != INVALID_HANDLE_VALUE)
655 /* FIXME: flush, do not commit */
656 if (_commit(i) == -1)
658 MSVCRT_files[i]->_flag |= MSVCRT__IOERR;
660 if(MSVCRT_files[i] && MSVCRT_files[i]->_flag & MSVCRT__IOWRT) {
661 MSVCRT_fflush(MSVCRT_files[i]);
666 TRACE(":flushed (%d) handles\n",num_flushed);
670 /*********************************************************************
673 int _fstat(int fd, struct _stat* buf)
676 BY_HANDLE_FILE_INFORMATION hfi;
677 HANDLE hand = msvcrt_fdtoh(fd);
679 TRACE(":fd (%d) stat (%p)\n",fd,buf);
680 if (hand == INVALID_HANDLE_VALUE)
685 WARN(":failed-NULL buf\n");
686 MSVCRT__set_errno(ERROR_INVALID_PARAMETER);
690 memset(&hfi, 0, sizeof(hfi));
691 memset(buf, 0, sizeof(struct _stat));
692 if (!GetFileInformationByHandle(hand, &hfi))
694 WARN(":failed-last error (%ld)\n",GetLastError());
695 MSVCRT__set_errno(ERROR_INVALID_PARAMETER);
698 FIXME(":dwFileAttributes = %ld, mode set to 0\n",hfi.dwFileAttributes);
699 buf->st_nlink = hfi.nNumberOfLinks;
700 buf->st_size = hfi.nFileSizeLow;
701 RtlTimeToSecondsSince1970(&hfi.ftLastAccessTime, &dw);
703 RtlTimeToSecondsSince1970(&hfi.ftLastWriteTime, &dw);
704 buf->st_mtime = buf->st_ctime = dw;
708 /*********************************************************************
711 int _futime(int fd, struct _utimbuf *t)
713 HANDLE hand = msvcrt_fdtoh(fd);
718 MSVCRT_time_t currTime;
719 MSVCRT_time(&currTime);
720 RtlSecondsSince1970ToTime(currTime, &at);
721 memcpy(&wt, &at, sizeof(wt));
725 RtlSecondsSince1970ToTime(t->actime, &at);
726 if (t->actime == t->modtime)
727 memcpy(&wt, &at, sizeof(wt));
729 RtlSecondsSince1970ToTime(t->modtime, &wt);
732 if (!SetFileTime(hand, NULL, &at, &wt))
734 MSVCRT__set_errno(GetLastError());
740 /*********************************************************************
741 * _get_osfhandle (MSVCRT.@)
743 long _get_osfhandle(int fd)
745 HANDLE hand = msvcrt_fdtoh(fd);
746 HANDLE newhand = hand;
747 TRACE(":fd (%d) handle (%d)\n",fd,hand);
749 if (hand != INVALID_HANDLE_VALUE)
751 /* FIXME: I'm not convinced that I should be copying the
752 * handle here - it may be leaked if the app doesn't
753 * close it (and the API docs dont say that it should)
754 * Not duplicating it means that it can't be inherited
755 * and so lcc's wedit doesn't cope when it passes it to
756 * child processes. I've an idea that it should either
757 * be copied by CreateProcess, or marked as inheritable
758 * when initialised, or maybe both? JG 21-9-00.
760 DuplicateHandle(GetCurrentProcess(),hand,GetCurrentProcess(),
761 &newhand,0,TRUE,DUPLICATE_SAME_ACCESS);
766 /*********************************************************************
771 HANDLE hand = msvcrt_fdtoh(fd);
773 TRACE(":fd (%d) handle (%d)\n",fd,hand);
774 if (hand == INVALID_HANDLE_VALUE)
777 return GetFileType(hand) == FILE_TYPE_CHAR? 1 : 0;
780 /*********************************************************************
783 char *_mktemp(char *pattern)
786 char *retVal = pattern;
791 numX = (*pattern++ == 'X')? numX + 1 : 0;
795 id = GetCurrentProcessId();
799 int tempNum = id / 10;
800 *pattern-- = id - (tempNum * 10) + '0';
806 if (GetFileAttributesA(retVal) == 0xFFFFFFFF &&
807 GetLastError() == ERROR_FILE_NOT_FOUND)
810 } while(letter != '|');
814 /*********************************************************************
815 * _wmktemp (MSVCRT.@)
817 WCHAR *_wmktemp(WCHAR *pattern)
820 WCHAR *retVal = pattern;
822 WCHAR letter = (WCHAR)L'a';
825 numX = (*pattern++ == (WCHAR)L'X')? numX + 1 : 0;
829 id = GetCurrentProcessId();
833 int tempNum = id / 10;
834 *pattern-- = id - (tempNum * 10) + (WCHAR)L'0';
840 if (GetFileAttributesW(retVal) == 0xFFFFFFFF &&
841 GetLastError() == ERROR_FILE_NOT_FOUND)
844 } while(letter != (WCHAR)L'|');
848 /*********************************************************************
851 int MSVCRT__sopen( const char *path, int oflags, int shflags, ... )
855 DWORD access = 0, creation = 0;
859 SECURITY_ATTRIBUTES sa;
862 TRACE(":file (%s) oflags: 0x%04x shflags: 0x%04x\n",
863 path, oflags, shflags);
865 switch(oflags & (_O_RDONLY | _O_WRONLY | _O_RDWR))
868 access |= GENERIC_READ;
869 ioflag |= MSVCRT__IOREAD;
872 access |= GENERIC_WRITE;
873 ioflag |= MSVCRT__IOWRT;
876 access |= GENERIC_WRITE | GENERIC_READ;
877 ioflag |= MSVCRT__IORW;
881 if (oflags & _O_CREAT)
883 va_start(ap, shflags);
884 pmode = va_arg(ap, int);
887 FIXME(": pmode 0x%04x ignored\n", pmode);
889 if (oflags & _O_EXCL)
890 creation = CREATE_NEW;
891 else if (oflags & _O_TRUNC)
892 creation = CREATE_ALWAYS;
894 creation = OPEN_ALWAYS;
896 else /* no _O_CREAT */
898 if (oflags & _O_TRUNC)
899 creation = TRUNCATE_EXISTING;
901 creation = OPEN_EXISTING;
903 if (oflags & _O_APPEND)
904 ioflag |= MSVCRT__IOAPPEND;
907 oflags |= _O_BINARY; /* FIXME: Default to text */
909 if (oflags & _O_TEXT)
911 /* Dont warn when writing */
912 if (ioflag & GENERIC_READ)
913 FIXME(":TEXT node not implemented\n");
923 sharing = FILE_SHARE_READ;
926 sharing = FILE_SHARE_WRITE;
929 sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
932 ERR( "Unhandled shflags 0x%x\n", shflags );
936 if (oflags & ~(_O_BINARY|_O_TEXT|_O_APPEND|_O_TRUNC|_O_EXCL
937 |_O_CREAT|_O_RDWR|_O_TEMPORARY|_O_NOINHERIT))
938 TRACE(":unsupported oflags 0x%04x\n",oflags);
940 sa.nLength = sizeof( SECURITY_ATTRIBUTES );
941 sa.lpSecurityDescriptor = NULL;
942 sa.bInheritHandle = (oflags & _O_NOINHERIT) ? FALSE : TRUE;
944 hand = CreateFileA(path, access, sharing,
945 &sa, creation, FILE_ATTRIBUTE_NORMAL, 0);
947 if (hand == INVALID_HANDLE_VALUE) {
948 WARN(":failed-last error (%ld)\n",GetLastError());
949 MSVCRT__set_errno(GetLastError());
953 fd = msvcrt_alloc_fd(hand, ioflag);
955 TRACE(":fd (%d) handle (%d)\n",fd, hand);
959 if (oflags & _O_TEMPORARY)
960 MSVCRT_tempfiles[fd] = _strdup(path);
961 if (ioflag & MSVCRT__IOAPPEND)
962 _lseek(fd, 0, FILE_END);
968 /*********************************************************************
971 int MSVCRT__wsopen( const WCHAR* path, int oflags, int shflags, ... )
973 const unsigned int len = strlenW(path);
974 char *patha = MSVCRT_calloc(len + 1,1);
978 va_start(ap, shflags);
979 pmode = va_arg(ap, int);
982 if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
984 int retval = MSVCRT__sopen(patha,oflags,shflags,pmode);
989 MSVCRT__set_errno(GetLastError());
993 /*********************************************************************
996 int _open( const char *path, int flags, ... )
1001 va_start(ap, flags);
1002 pmode = va_arg(ap, int);
1005 return MSVCRT__sopen( path, flags, _SH_DENYNO, pmode );
1008 /*********************************************************************
1011 int _wopen(const WCHAR *path,int flags,...)
1013 const unsigned int len = strlenW(path);
1014 char *patha = MSVCRT_calloc(len + 1,1);
1018 va_start(ap, flags);
1019 pmode = va_arg(ap, int);
1022 if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
1024 int retval = _open(patha,flags,pmode);
1029 MSVCRT__set_errno(GetLastError());
1033 /*********************************************************************
1036 int _creat(const char *path, int flags)
1038 int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
1039 return _open(path, usedFlags);
1042 /*********************************************************************
1043 * _wcreat (MSVCRT.@)
1045 int _wcreat(const WCHAR *path, int flags)
1047 int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
1048 return _wopen(path, usedFlags);
1051 /*********************************************************************
1052 * _open_osfhandle (MSVCRT.@)
1054 int _open_osfhandle(long hand, int flags)
1056 /* _O_RDONLY (0) always matches, so set the read flag*/
1057 /* FIXME: handle more flags */
1058 int fd= msvcrt_alloc_fd(hand,flags|MSVCRT__IOREAD);
1059 TRACE(":handle (%ld) fd (%d) flags 0x%08x\n",hand,fd, flags |MSVCRT__IOREAD);
1063 /*********************************************************************
1068 int num_removed = 0, i;
1070 for (i = 3; i < MSVCRT_fdend; i++)
1071 if (MSVCRT_tempfiles[i])
1078 TRACE(":removed (%d) temp files\n",num_removed);
1082 /*********************************************************************
1085 int _read(int fd, void *buf, unsigned int count)
1088 HANDLE hand = msvcrt_fdtoh(fd);
1090 /* Dont trace small reads, it gets *very* annoying */
1092 TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
1093 if (hand == INVALID_HANDLE_VALUE)
1096 if (ReadFile(hand, buf, count, &num_read, NULL))
1098 if (num_read != count && MSVCRT_files[fd])
1101 MSVCRT_flags[fd] |= MSVCRT__IOEOF;
1103 MSVCRT_files[fd]->_flag |= MSVCRT__IOEOF;
1108 TRACE(":failed-last error (%ld)\n",GetLastError());
1109 if (MSVCRT_files[fd])
1110 MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
1114 /*********************************************************************
1117 int _getw(MSVCRT_FILE* file)
1120 if (_read(file->_file, &i, sizeof(int)) != 1)
1125 /*********************************************************************
1126 * _setmode (MSVCRT.@)
1128 int _setmode(int fd,int mode)
1131 FIXME("fd (%d) mode (%d) TEXT not implemented\n",fd,mode);
1135 /*********************************************************************
1138 int _stat(const char* path, struct _stat * buf)
1141 WIN32_FILE_ATTRIBUTE_DATA hfi;
1142 unsigned short mode = MSVCRT_S_IREAD;
1145 TRACE(":file (%s) buf(%p)\n",path,buf);
1147 if (!GetFileAttributesExA(path, GetFileExInfoStandard, &hfi))
1149 TRACE("failed (%ld)\n",GetLastError());
1150 MSVCRT__set_errno(ERROR_FILE_NOT_FOUND);
1154 memset(buf,0,sizeof(struct _stat));
1156 /* FIXME: rdev isnt drive num,despite what the docs say-what is it?
1157 Bon 011120: This FIXME seems incorrect
1158 Also a letter as first char isn't enough to be classify
1161 if (isalpha(*path)&& (*(path+1)==':'))
1162 buf->st_dev = buf->st_rdev = toupper(*path) - 'A'; /* drive num */
1164 buf->st_dev = buf->st_rdev = _getdrive() - 1;
1166 plen = strlen(path);
1168 /* Dir, or regular file? */
1169 if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1170 (path[plen-1] == '\\'))
1171 mode |= (_S_IFDIR | MSVCRT_S_IEXEC);
1176 if (plen > 6 && path[plen-4] == '.') /* shortest exe: "\x.exe" */
1178 unsigned int ext = tolower(path[plen-1]) | (tolower(path[plen-2]) << 8) |
1179 (tolower(path[plen-3]) << 16);
1180 if (ext == EXE || ext == BAT || ext == CMD || ext == COM)
1181 mode |= MSVCRT_S_IEXEC;
1185 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1186 mode |= MSVCRT_S_IWRITE;
1188 buf->st_mode = mode;
1190 buf->st_size = hfi.nFileSizeLow;
1191 RtlTimeToSecondsSince1970(&hfi.ftLastAccessTime, &dw);
1193 RtlTimeToSecondsSince1970(&hfi.ftLastWriteTime, &dw);
1194 buf->st_mtime = buf->st_ctime = dw;
1195 TRACE("\n%d %d %d %ld %ld %ld\n", buf->st_mode,buf->st_nlink,buf->st_size,
1196 buf->st_atime,buf->st_mtime, buf->st_ctime);
1200 /*********************************************************************
1203 int _wstat(const WCHAR* path, struct _stat * buf)
1206 WIN32_FILE_ATTRIBUTE_DATA hfi;
1207 unsigned short mode = MSVCRT_S_IREAD;
1210 TRACE(":file (%s) buf(%p)\n",debugstr_w(path),buf);
1212 if (!GetFileAttributesExW(path, GetFileExInfoStandard, &hfi))
1214 TRACE("failed (%ld)\n",GetLastError());
1215 MSVCRT__set_errno(ERROR_FILE_NOT_FOUND);
1219 memset(buf,0,sizeof(struct _stat));
1221 /* FIXME: rdev isn't drive num, despite what the docs says-what is it? */
1222 if (MSVCRT_iswalpha(*path))
1223 buf->st_dev = buf->st_rdev = toupperW(*path - (WCHAR)L'A'); /* drive num */
1225 buf->st_dev = buf->st_rdev = _getdrive() - 1;
1227 plen = strlenW(path);
1229 /* Dir, or regular file? */
1230 if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1231 (path[plen-1] == (WCHAR)L'\\'))
1232 mode |= (_S_IFDIR | MSVCRT_S_IEXEC);
1237 if (plen > 6 && path[plen-4] == (WCHAR)L'.') /* shortest exe: "\x.exe" */
1239 ULONGLONG ext = tolowerW(path[plen-1]) | (tolowerW(path[plen-2]) << 16) |
1240 ((ULONGLONG)tolowerW(path[plen-3]) << 32);
1241 if (ext == WCEXE || ext == WCBAT || ext == WCCMD || ext == WCCOM)
1242 mode |= MSVCRT_S_IEXEC;
1246 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1247 mode |= MSVCRT_S_IWRITE;
1249 buf->st_mode = mode;
1251 buf->st_size = hfi.nFileSizeLow;
1252 RtlTimeToSecondsSince1970(&hfi.ftLastAccessTime, &dw);
1254 RtlTimeToSecondsSince1970(&hfi.ftLastWriteTime, &dw);
1255 buf->st_mtime = buf->st_ctime = dw;
1256 TRACE("\n%d %d %d %ld %ld %ld\n", buf->st_mode,buf->st_nlink,buf->st_size,
1257 buf->st_atime,buf->st_mtime, buf->st_ctime);
1261 /*********************************************************************
1266 return _lseek(fd, 0, SEEK_CUR);
1269 /*********************************************************************
1270 * _tempnam (MSVCRT.@)
1272 char *_tempnam(const char *dir, const char *prefix)
1274 char tmpbuf[MAX_PATH];
1276 TRACE("dir (%s) prefix (%s)\n",dir,prefix);
1277 if (GetTempFileNameA(dir,prefix,0,tmpbuf))
1279 TRACE("got name (%s)\n",tmpbuf);
1280 return _strdup(tmpbuf);
1282 TRACE("failed (%ld)\n",GetLastError());
1286 /*********************************************************************
1287 * _wtempnam (MSVCRT.@)
1289 WCHAR *_wtempnam(const WCHAR *dir, const WCHAR *prefix)
1291 WCHAR tmpbuf[MAX_PATH];
1293 TRACE("dir (%s) prefix (%s)\n",debugstr_w(dir),debugstr_w(prefix));
1294 if (GetTempFileNameW(dir,prefix,0,tmpbuf))
1296 TRACE("got name (%s)\n",debugstr_w(tmpbuf));
1297 return _wcsdup(tmpbuf);
1299 TRACE("failed (%ld)\n",GetLastError());
1303 /*********************************************************************
1306 int _umask(int umask)
1308 int old_umask = MSVCRT_umask;
1309 TRACE("(%d)\n",umask);
1310 MSVCRT_umask = umask;
1314 /*********************************************************************
1317 int _utime(const char* path, struct _utimbuf *t)
1319 int fd = _open(path, _O_WRONLY | _O_BINARY);
1323 int retVal = _futime(fd, t);
1330 /*********************************************************************
1331 * _wutime (MSVCRT.@)
1333 int _wutime(const WCHAR* path, struct _utimbuf *t)
1335 int fd = _wopen(path, _O_WRONLY | _O_BINARY);
1339 int retVal = _futime(fd, t);
1346 /*********************************************************************
1349 int _write(int fd, const void* buf, unsigned int count)
1352 HANDLE hand = msvcrt_fdtoh(fd);
1354 /* Dont trace small writes, it gets *very* annoying */
1357 TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
1359 if (hand == INVALID_HANDLE_VALUE)
1362 /* If appending, go to EOF */
1363 if (MSVCRT_flags[fd] & MSVCRT__IOAPPEND)
1364 _lseek(fd, 0, FILE_END);
1366 if (WriteFile(hand, buf, count, &num_written, NULL)
1367 && (num_written == count))
1370 TRACE(":failed-last error (%ld)\n",GetLastError());
1371 if (MSVCRT_files[fd])
1372 MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
1377 /*********************************************************************
1380 int _putw(int val, MSVCRT_FILE* file)
1382 return _write(file->_file, &val, sizeof(val)) == 1? val : MSVCRT_EOF;
1385 /*********************************************************************
1386 * clearerr (MSVCRT.@)
1388 void MSVCRT_clearerr(MSVCRT_FILE* file)
1390 TRACE(":file (%p) fd (%d)\n",file,file->_file);
1391 file->_flag &= ~(MSVCRT__IOERR | MSVCRT__IOEOF);
1394 /*********************************************************************
1397 int MSVCRT_fclose(MSVCRT_FILE* file)
1400 r=_close(file->_file);
1401 return ((r==MSVCRT_EOF) || (file->_flag & MSVCRT__IOERR) ? MSVCRT_EOF : 0);
1404 /*********************************************************************
1407 int MSVCRT_feof(MSVCRT_FILE* file)
1409 return file->_flag & MSVCRT__IOEOF;
1412 /*********************************************************************
1415 int MSVCRT_ferror(MSVCRT_FILE* file)
1417 return file->_flag & MSVCRT__IOERR;
1420 /*********************************************************************
1423 int MSVCRT_fflush(MSVCRT_FILE* file)
1429 int res=msvcrt_flush_buffer(file);
1434 /*********************************************************************
1437 int MSVCRT_fgetc(MSVCRT_FILE* file)
1441 return *(unsigned char *)file->_ptr++;
1443 return _filbuf(file);
1447 /*********************************************************************
1448 * _fgetchar (MSVCRT.@)
1452 return MSVCRT_fgetc(MSVCRT_stdin);
1455 /*********************************************************************
1456 * _filbuf (MSVCRT.@)
1458 int _filbuf(MSVCRT_FILE* file)
1461 /* Allocate buffer if needed */
1462 if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF) ) {
1463 msvcrt_alloc_buffer(file);
1465 if(!(file->_flag & MSVCRT__IOREAD)) {
1466 if(file->_flag & MSVCRT__IORW) {
1467 file->_flag |= MSVCRT__IOREAD;
1472 if(file->_flag & MSVCRT__IONBF) {
1474 if (_read(file->_file,&c,1) != 1) {
1475 file->_flag |= MSVCRT__IOEOF;
1480 file->_cnt = _read(file->_file, file->_base, file->_bufsiz);
1481 if(file->_cnt<0) file->_cnt = 0;
1483 file->_flag |= MSVCRT__IOEOF;
1487 file->_ptr = file->_base+1;
1488 return *(unsigned char *)file->_base;
1492 /*********************************************************************
1493 * fgetpos (MSVCRT.@)
1495 int MSVCRT_fgetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
1497 *pos = MSVCRT_ftell(file);
1498 return (*pos == -1? -1 : 0);
1501 /*********************************************************************
1504 char *MSVCRT_fgets(char *s, int size, MSVCRT_FILE* file)
1507 char * buf_start = s;
1509 TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
1510 file,file->_file,s,size);
1512 for(cc = MSVCRT_fgetc(file); cc != MSVCRT_EOF && cc != '\n';
1513 cc = MSVCRT_fgetc(file))
1516 if (--size <= 0) break;
1519 if ((cc == MSVCRT_EOF) && (s == buf_start)) /* If nothing read, return 0*/
1521 TRACE(":nothing read\n");
1528 TRACE(":got '%s'\n", buf_start);
1532 /*********************************************************************
1535 MSVCRT_wint_t MSVCRT_fgetwc(MSVCRT_FILE* file)
1538 if (_read(file->_file, &wc, sizeof(wc)) != sizeof(wc))
1543 /*********************************************************************
1546 MSVCRT_wint_t MSVCRT_getwc(MSVCRT_FILE* file)
1548 return MSVCRT_fgetwc(file);
1551 /*********************************************************************
1552 * _fgetwchar (MSVCRT.@)
1554 MSVCRT_wint_t _fgetwchar(void)
1556 return MSVCRT_fgetwc(MSVCRT_stdin);
1559 /*********************************************************************
1560 * getwchar (MSVCRT.@)
1562 MSVCRT_wint_t MSVCRT_getwchar(void)
1564 return _fgetwchar();
1567 /*********************************************************************
1570 WCHAR *MSVCRT_fgetws(WCHAR *s, int size, MSVCRT_FILE* file)
1573 WCHAR * buf_start = s;
1575 TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
1576 file,file->_file,s,size);
1578 for(cc = MSVCRT_fgetwc(file); cc != MSVCRT_WEOF && cc != L'\n';
1579 cc = MSVCRT_fgetwc(file))
1582 if (--size <= 0) break;
1585 if ((cc == MSVCRT_EOF) && (s == buf_start)) /* If nothing read, return 0*/
1587 TRACE(":nothing read\n");
1594 /* TRACE(":got '%s'\n", buf_start); */
1599 /*********************************************************************
1602 MSVCRT_wint_t MSVCRT_fputwc(MSVCRT_wint_t wc, MSVCRT_FILE* file)
1605 if (MSVCRT_fwrite( &mwc, sizeof(mwc), 1, file) != 1)
1610 /*********************************************************************
1611 * _fputwchar (MSVCRT.@)
1613 MSVCRT_wint_t _fputwchar(MSVCRT_wint_t wc)
1615 return MSVCRT_fputwc(wc, MSVCRT_stdout);
1618 /*********************************************************************
1621 MSVCRT_FILE* MSVCRT_fopen(const char *path, const char *mode)
1624 int flags = 0, plus = 0, fd;
1625 const char* search = mode;
1627 TRACE("(%s,%s)\n",path,mode);
1630 if (*search++ == '+')
1633 /* map mode string to open() flags. "man fopen" for possibilities. */
1637 flags = (plus ? _O_RDWR : _O_RDONLY);
1640 flags = _O_CREAT | _O_TRUNC | (plus ? _O_RDWR : _O_WRONLY);
1643 flags = _O_CREAT | _O_APPEND | (plus ? _O_RDWR : _O_WRONLY);
1658 flags &= ~_O_BINARY;
1663 FIXME(":unknown flag %c not supported\n",mode[-1]);
1666 fd = _open(path, flags);
1671 file = msvcrt_alloc_fp(fd);
1672 TRACE(":got (%p)\n",file);
1679 /*********************************************************************
1680 * _wfopen (MSVCRT.@)
1682 MSVCRT_FILE *_wfopen(const WCHAR *path, const WCHAR *mode)
1684 const unsigned int plen = strlenW(path), mlen = strlenW(mode);
1685 char *patha = MSVCRT_calloc(plen + 1, 1);
1686 char *modea = MSVCRT_calloc(mlen + 1, 1);
1688 TRACE("(%s,%s)\n",debugstr_w(path),debugstr_w(mode));
1690 if (patha && modea &&
1691 WideCharToMultiByte(CP_ACP,0,path,plen,patha,plen,NULL,NULL) &&
1692 WideCharToMultiByte(CP_ACP,0,mode,mlen,modea,mlen,NULL,NULL))
1694 MSVCRT_FILE *retval = MSVCRT_fopen(patha,modea);
1700 MSVCRT__set_errno(GetLastError());
1704 /*********************************************************************
1705 * _fsopen (MSVCRT.@)
1707 MSVCRT_FILE* _fsopen(const char *path, const char *mode, int share)
1709 FIXME(":(%s,%s,%d),ignoring share mode!\n",path,mode,share);
1710 return MSVCRT_fopen(path,mode);
1713 /*********************************************************************
1714 * _wfsopen (MSVCRT.@)
1716 MSVCRT_FILE* _wfsopen(const WCHAR *path, const WCHAR *mode, int share)
1718 FIXME(":(%s,%s,%d),ignoring share mode!\n",
1719 debugstr_w(path),debugstr_w(mode),share);
1720 return _wfopen(path,mode);
1723 /*********************************************************************
1726 int MSVCRT_fputc(int c, MSVCRT_FILE* file)
1733 return _flsbuf(c, file);
1737 /*********************************************************************
1738 * _flsbuf (MSVCRT.@)
1740 int _flsbuf(int c, MSVCRT_FILE* file)
1742 /* Flush output buffer */
1743 if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
1744 msvcrt_alloc_buffer(file);
1746 if(!(file->_flag & MSVCRT__IOWRT)) {
1747 if(file->_flag & MSVCRT__IORW) {
1748 file->_flag |= MSVCRT__IOWRT;
1754 int res=msvcrt_flush_buffer(file);
1755 return res?res : MSVCRT_fputc(c, file);
1758 return _write(file->_file, &cc, 1) == 1? c : MSVCRT_EOF;
1762 /*********************************************************************
1763 * _fputchar (MSVCRT.@)
1765 int _fputchar(int c)
1767 return MSVCRT_fputc(c, MSVCRT_stdout);
1770 /*********************************************************************
1773 MSVCRT_size_t MSVCRT_fread(void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
1774 { MSVCRT_size_t rcnt=size * nmemb;
1775 MSVCRT_size_t read=0;
1777 /* first buffered data */
1779 int pcnt= (rcnt>file->_cnt)? file->_cnt:rcnt;
1780 memcpy(ptr, file->_ptr, pcnt);
1785 ptr = (char*)ptr + pcnt;
1786 } else if(!(file->_flag & MSVCRT__IOREAD )) {
1787 if(file->_flag & MSVCRT__IORW) {
1788 file->_flag |= MSVCRT__IOREAD;
1792 if(rcnt) pread = _read(file->_file,ptr, rcnt);
1793 if (MSVCRT_flags[file->_file] & MSVCRT__IOEOF)
1794 /* expose feof condition in the flags
1795 MFC tests file->_flag for feof, and doesn't not call feof())
1797 file->_flag |= MSVCRT__IOEOF;
1804 /*********************************************************************
1805 * freopen (MSVCRT.@)
1808 MSVCRT_FILE* MSVCRT_freopen(const char *path, const char *mode,MSVCRT_FILE* file)
1810 MSVCRT_FILE* newfile;
1813 TRACE(":path (%p) mode (%s) file (%p) fd (%d)\n",path,mode,file,file->_file);
1814 if (!file || ((fd = file->_file) < 0) || fd > MSVCRT_fdend)
1820 FIXME(":reopen on user file not implemented!\n");
1821 MSVCRT__set_errno(ERROR_CALL_NOT_IMPLEMENTED);
1824 if(MSVCRT_fclose(file))
1826 return MSVCRT_fopen(path, mode);
1829 /* first, create the new file */
1830 if ((newfile = MSVCRT_fopen(path,mode)) == NULL)
1833 if (fd < 3 && SetStdHandle(fd == 0 ? STD_INPUT_HANDLE :
1834 (fd == 1? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE),
1835 MSVCRT_handles[newfile->_file]))
1837 /* Redirecting std handle to file , copy over.. */
1838 MSVCRT_handles[fd] = MSVCRT_handles[newfile->_file];
1839 MSVCRT_flags[fd] = MSVCRT_flags[newfile->_file];
1840 memcpy(&MSVCRT__iob[fd], newfile, sizeof (MSVCRT_FILE));
1841 MSVCRT__iob[fd]._file = fd;
1842 /* And free up the resources allocated by fopen, but
1843 * not the HANDLE we copied. */
1844 MSVCRT_free(MSVCRT_files[fd]);
1845 msvcrt_free_fd(newfile->_file);
1846 return &MSVCRT__iob[fd];
1849 WARN(":failed-last error (%ld)\n",GetLastError());
1850 MSVCRT_fclose(newfile);
1851 MSVCRT__set_errno(GetLastError());
1855 /*********************************************************************
1856 * fsetpos (MSVCRT.@)
1858 int MSVCRT_fsetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
1860 return _lseek(file->_file,*pos,SEEK_SET);
1863 /* helper function for fscanf. Returns the value of character c in the
1864 * given base, or -1 if the given character is not a digit of the base.
1866 static int char2digit(char c, int base) {
1867 if ((c>='0') && (c<='9') && (c<='0'+base-1)) return (c-'0');
1868 if (base<=10) return -1;
1869 if ((c>='A') && (c<='Z') && (c<='A'+base-11)) return (c-'A'+10);
1870 if ((c>='a') && (c<='z') && (c<='a'+base-11)) return (c-'a'+10);
1874 /*********************************************************************
1876 * Implemented based on
1877 * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/html/_crt_format_specification_fields_.2d_.scanf_and_wscanf_functions.asp
1878 * Extended by C. Scott Ananian <cananian@alumni.princeton.edu> to handle
1879 * more types of format spec.
1881 int MSVCRT_fscanf(MSVCRT_FILE* file, const char *format, ...)
1883 /* NOTE: If you extend this function, extend MSVCRT__cscanf in console.c too */
1887 if (!*format) return 0;
1888 WARN("%p (\"%s\"): semi-stub\n", file, format);
1889 nch = MSVCRT_fgetc(file);
1890 va_start(ap, format);
1892 /* a whitespace character in the format string causes scanf to read,
1893 * but not store, all consecutive white-space characters in the input
1894 * up to the next non-white-space character. One white space character
1895 * in the input matches any number (including zero) and combination of
1896 * white-space characters in the input. */
1897 if (isspace(*format)) {
1898 /* skip whitespace */
1899 while ((nch!=MSVCRT_EOF) && isspace(nch))
1900 nch = MSVCRT_fgetc(file);
1902 /* a format specification causes scanf to read and convert characters
1903 * in the input into values of a specified type. The value is assigned
1904 * to an argument in the argument list. Format specifications have
1905 * the form %[*][width][{h | l | I64 | L}]type */
1906 /* FIXME: unimplemented: h/l/I64/L modifiers and some type specs. */
1907 else if (*format == '%') {
1908 int st = 0; int suppress = 0; int width = 0;
1909 int base, number_signed;
1911 /* look for leading asterisk, which means 'suppress assignment of
1917 /* look for width specification */
1918 while (isdigit(*format)) {
1920 width+=*format++ - '0';
1922 if (width==0) width=-1; /* no width spec seen */
1924 case '%': /* read a percent symbol */
1925 if (nch!='%') break;
1926 nch = MSVCRT_fgetc(file);
1929 case 'X': /* hexadecimal integer. */
1930 base = 16; number_signed = 0;
1932 case 'o': /* octal integer */
1933 base = 8; number_signed = 0;
1935 case 'u': /* unsigned decimal integer */
1936 base = 10; number_signed = 0;
1938 case 'd': /* signed decimal integer */
1939 base = 10; number_signed = 1;
1941 case 'i': /* generic integer */
1942 base = 0; number_signed = 1;
1944 /* read an integer */
1945 int*val = suppress ? NULL : va_arg(ap, int*);
1946 int cur = 0; int negative = 0; int seendigit=0;
1947 /* skip initial whitespace */
1948 while ((nch!=MSVCRT_EOF) && isspace(nch))
1949 nch = MSVCRT_fgetc(file);
1951 if (number_signed && (nch == '-' || nch == '+')) {
1952 negative = (nch=='-');
1953 nch = MSVCRT_fgetc(file);
1954 if (width>0) width--;
1956 /* look for leading indication of base */
1957 if (width!=0 && nch == '0') {
1958 nch = MSVCRT_fgetc(file);
1959 if (width>0) width--;
1961 if (width!=0 && (nch=='x' || nch=='X')) {
1965 nch = MSVCRT_fgetc(file);
1966 if (width>0) width--;
1974 /* throw away leading zeros */
1975 while (width!=0 && nch=='0') {
1976 nch = MSVCRT_fgetc(file);
1977 if (width>0) width--;
1980 /* get first digit. Keep working copy negative, as the
1981 * range of negative numbers in two's complement notation
1982 * is one larger than the range of positive numbers. */
1983 if (width!=0 && char2digit(nch, base)!=-1) {
1984 cur = -char2digit(nch, base);
1985 nch = MSVCRT_fgetc(file);
1986 if (width>0) width--;
1989 /* read until no more digits */
1990 while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
1991 cur = cur*base + char2digit(nch, base);
1992 nch = MSVCRT_fgetc(file);
1993 if (width>0) width--;
1996 /* negate parsed number if non-negative */
1997 if (!negative) cur=-cur;
1999 if (!seendigit) break; /* not a valid number */
2001 if (!suppress) *val = cur;
2008 case 'G': { /* read a float */
2009 float*val = suppress ? NULL : va_arg(ap, float*);
2012 /* skip initial whitespace */
2013 while ((nch!=MSVCRT_EOF) && isspace(nch))
2014 nch = MSVCRT_fgetc(file);
2016 if (nch == '-' || nch == '+') {
2017 negative = (nch=='-');
2018 if (width>0) width--;
2019 if (width==0) break;
2020 nch = MSVCRT_fgetc(file);
2022 /* get first digit. */
2023 if (!isdigit(nch)) break;
2024 cur = (nch - '0') * (negative ? -1 : 1);
2025 nch = MSVCRT_fgetc(file);
2026 if (width>0) width--;
2027 /* read until no more digits */
2028 while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
2029 cur = cur*10 + (nch - '0');
2030 nch = MSVCRT_fgetc(file);
2031 if (width>0) width--;
2033 /* handle decimals */
2034 if (width!=0 && nch == '.') {
2036 nch = MSVCRT_fgetc(file);
2037 if (width>0) width--;
2038 while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
2040 cur += dec * (nch - '0');
2041 nch = MSVCRT_fgetc(file);
2042 if (width>0) width--;
2045 /* handle exponent */
2046 if (width!=0 && (nch == 'e' || nch == 'E')) {
2047 int exponent = 0, negexp = 0;
2049 nch = MSVCRT_fgetc(file);
2050 if (width>0) width--;
2051 /* possible sign on the exponent */
2052 if (width!=0 && (nch=='+' || nch=='-')) {
2053 negexp = (nch=='-');
2054 nch = MSVCRT_fgetc(file);
2055 if (width>0) width--;
2057 /* exponent digits */
2058 while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
2060 exponent += (nch - '0');
2061 nch = MSVCRT_fgetc(file);
2062 if (width>0) width--;
2064 /* update 'cur' with this exponent. */
2065 expcnt = negexp ? .1 : 10;
2066 while (exponent!=0) {
2070 expcnt=expcnt*expcnt;
2074 if (!suppress) *val = cur;
2077 case 's': { /* read a word */
2078 char*str = suppress ? NULL : va_arg(ap, char*);
2080 /* skip initial whitespace */
2081 while ((nch!=MSVCRT_EOF) && isspace(nch))
2082 nch = MSVCRT_fgetc(file);
2083 /* read until whitespace */
2084 while (width!=0 && (nch!=MSVCRT_EOF) && !isspace(nch)) {
2085 if (!suppress) *sptr++ = nch;
2087 nch = MSVCRT_fgetc(file);
2088 if (width>0) width--;
2091 if (!suppress) *sptr = 0;
2092 TRACE("read word: %s\n", str);
2095 default: FIXME("unhandled: %%%c\n", *format);
2096 /* From spec: "if a percent sign is followed by a character
2097 * that has no meaning as a format-control character, that
2098 * character and the following characters are treated as
2099 * an ordinary sequence of characters, that is, a sequence
2100 * of characters that must match the input. For example,
2101 * to specify that a percent-sign character is to be input,
2103 * LEAVING AS-IS because we catch bugs better that way. */
2105 if (st && !suppress) rd++;
2108 /* a non-white-space character causes scanf to read, but not store,
2109 * a matching non-white-space character. */
2111 /* check for character match */
2113 nch = MSVCRT_fgetc(file);
2118 if (nch!=MSVCRT_EOF) {
2119 FIXME("need ungetch\n");
2122 TRACE("returning %d\n", rd);
2126 /*********************************************************************
2129 int MSVCRT_fseek(MSVCRT_FILE* file, long offset, int whence)
2131 /* Flush output if needed */
2132 if(file->_flag & MSVCRT__IOWRT)
2133 msvcrt_flush_buffer(file);
2135 if(whence == SEEK_CUR && file->_flag & MSVCRT__IOREAD ) {
2136 offset -= file->_cnt;
2138 /* Discard buffered input */
2140 file->_ptr = file->_base;
2141 /* Reset direction of i/o */
2142 if(file->_flag & MSVCRT__IORW) {
2143 file->_flag &= ~(MSVCRT__IOREAD|MSVCRT__IOWRT);
2145 return (_lseek(file->_file,offset,whence) == -1)?-1:0;
2148 /*********************************************************************
2151 LONG MSVCRT_ftell(MSVCRT_FILE* file)
2156 if( file->_flag & MSVCRT__IOWRT ) {
2157 off = file->_ptr - file->_base;
2162 pos = _tell(file->_file);
2163 if(pos == -1) return pos;
2167 /*********************************************************************
2170 MSVCRT_size_t MSVCRT_fwrite(const void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
2172 MSVCRT_size_t wrcnt=size * nmemb;
2177 int pcnt=(file->_cnt>wrcnt)? wrcnt: file->_cnt;
2178 memcpy(file->_ptr, ptr, pcnt);
2183 ptr = (char*)ptr + pcnt;
2184 } else if(!(file->_flag & MSVCRT__IOWRT)) {
2185 if(file->_flag & MSVCRT__IORW) {
2186 file->_flag |= MSVCRT__IOWRT;
2192 int res=msvcrt_flush_buffer(file);
2194 int pwritten = _write(file->_file, ptr, wrcnt);
2195 if (pwritten <= 0) pwritten=0;
2196 written += pwritten;
2199 return written / size;
2202 /*********************************************************************
2205 int MSVCRT_fputs(const char *s, MSVCRT_FILE* file)
2207 size_t len = strlen(s);
2208 return MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
2211 /*********************************************************************
2214 int MSVCRT_fputws(const WCHAR *s, MSVCRT_FILE* file)
2216 size_t len = strlenW(s);
2217 return MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
2220 /*********************************************************************
2221 * getchar (MSVCRT.@)
2223 int MSVCRT_getchar(void)
2225 return MSVCRT_fgetc(MSVCRT_stdin);
2228 /*********************************************************************
2231 int MSVCRT_getc(MSVCRT_FILE* file)
2233 return MSVCRT_fgetc(file);
2236 /*********************************************************************
2239 char *MSVCRT_gets(char *buf)
2242 char * buf_start = buf;
2244 for(cc = MSVCRT_fgetc(MSVCRT_stdin); cc != MSVCRT_EOF && cc != '\n';
2245 cc = MSVCRT_fgetc(MSVCRT_stdin))
2246 if(cc != '\r') *buf++ = (char)cc;
2250 TRACE("got '%s'\n", buf_start);
2254 /*********************************************************************
2257 WCHAR* MSVCRT__getws(WCHAR* buf)
2262 for (cc = MSVCRT_fgetwc(MSVCRT_stdin); cc != MSVCRT_WEOF && cc != '\n';
2263 cc = MSVCRT_fgetwc(MSVCRT_stdin))
2270 TRACE("got '%s'\n", debugstr_w(ws));
2274 /*********************************************************************
2277 int MSVCRT_putc(int c, MSVCRT_FILE* file)
2279 return MSVCRT_fputc(c, file);
2282 /*********************************************************************
2283 * putchar (MSVCRT.@)
2285 int MSVCRT_putchar(int c)
2287 return MSVCRT_fputc(c, MSVCRT_stdout);
2290 /*********************************************************************
2293 int MSVCRT_puts(const char *s)
2295 size_t len = strlen(s);
2296 if (MSVCRT_fwrite(s,sizeof(*s),len,MSVCRT_stdout) != len) return MSVCRT_EOF;
2297 return MSVCRT_fwrite("\n",1,1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
2300 /*********************************************************************
2303 int _putws(const WCHAR *s)
2305 static const WCHAR nl = '\n';
2306 size_t len = strlenW(s);
2307 if (MSVCRT_fwrite(s,sizeof(*s),len,MSVCRT_stdout) != len) return MSVCRT_EOF;
2308 return MSVCRT_fwrite(&nl,sizeof(nl),1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
2311 /*********************************************************************
2314 int MSVCRT_remove(const char *path)
2316 TRACE("(%s)\n",path);
2317 if (DeleteFileA(path))
2319 TRACE(":failed (%ld)\n",GetLastError());
2320 MSVCRT__set_errno(GetLastError());
2324 /*********************************************************************
2325 * _wremove (MSVCRT.@)
2327 int _wremove(const WCHAR *path)
2329 TRACE("(%s)\n",debugstr_w(path));
2330 if (DeleteFileW(path))
2332 TRACE(":failed (%ld)\n",GetLastError());
2333 MSVCRT__set_errno(GetLastError());
2337 /*********************************************************************
2340 int MSVCRT_scanf(const char *format, ...)
2345 va_start(valist, format);
2346 res = MSVCRT_fscanf(MSVCRT_stdin, format, valist);
2351 /*********************************************************************
2354 int MSVCRT_rename(const char *oldpath,const char *newpath)
2356 TRACE(":from %s to %s\n",oldpath,newpath);
2357 if (MoveFileExA(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
2359 TRACE(":failed (%ld)\n",GetLastError());
2360 MSVCRT__set_errno(GetLastError());
2364 /*********************************************************************
2365 * _wrename (MSVCRT.@)
2367 int _wrename(const WCHAR *oldpath,const WCHAR *newpath)
2369 TRACE(":from %s to %s\n",debugstr_w(oldpath),debugstr_w(newpath));
2370 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
2372 TRACE(":failed (%ld)\n",GetLastError());
2373 MSVCRT__set_errno(GetLastError());
2377 /*********************************************************************
2378 * setvbuf (MSVCRT.@)
2380 int MSVCRT_setvbuf(MSVCRT_FILE* file, char *buf, int mode, MSVCRT_size_t size)
2382 /* TODO: Check if file busy */
2384 MSVCRT_free(file->_base);
2388 if(mode == MSVCRT__IOFBF) {
2389 file->_flag &= ~MSVCRT__IONBF;
2390 file->_base = file->_ptr = buf;
2392 file->_bufsiz = size;
2395 file->_flag |= MSVCRT__IONBF;
2400 /*********************************************************************
2403 void MSVCRT_setbuf(MSVCRT_FILE* file, char *buf)
2405 MSVCRT_setvbuf(file, buf, buf ? MSVCRT__IOFBF : MSVCRT__IONBF, MSVCRT_BUFSIZ);
2408 /*********************************************************************
2411 char *MSVCRT_tmpnam(char *s)
2413 char tmpbuf[MAX_PATH];
2414 char* prefix = "TMP";
2415 if (!GetTempPathA(MAX_PATH,tmpbuf) ||
2416 !GetTempFileNameA(tmpbuf,prefix,0,MSVCRT_tmpname))
2418 TRACE(":failed-last error (%ld)\n",GetLastError());
2421 TRACE(":got tmpnam %s\n",MSVCRT_tmpname);
2426 /*********************************************************************
2427 * tmpfile (MSVCRT.@)
2429 MSVCRT_FILE* MSVCRT_tmpfile(void)
2431 char *filename = MSVCRT_tmpnam(NULL);
2433 fd = _open(filename, _O_CREAT | _O_BINARY | _O_RDWR | _O_TEMPORARY);
2435 return msvcrt_alloc_fp(fd);
2439 /*********************************************************************
2440 * vfprintf (MSVCRT.@)
2442 int MSVCRT_vfprintf(MSVCRT_FILE* file, const char *format, va_list valist)
2444 char buf[2048], *mem = buf;
2445 int written, resize = sizeof(buf), retval;
2446 /* There are two conventions for vsnprintf failing:
2447 * Return -1 if we truncated, or
2448 * Return the number of bytes that would have been written
2449 * The code below handles both cases
2451 while ((written = vsnprintf(mem, resize, format, valist)) == -1 ||
2454 resize = (written == -1 ? resize * 2 : written + 1);
2457 if (!(mem = (char *)MSVCRT_malloc(resize)))
2460 retval = MSVCRT_fwrite(mem, sizeof(*mem), written, file);
2466 /*********************************************************************
2467 * vfwprintf (MSVCRT.@)
2469 * Is final char included in written (then resize is too big) or not
2470 * (then we must test for equality too)?
2472 int MSVCRT_vfwprintf(MSVCRT_FILE* file, const WCHAR *format, va_list valist)
2474 WCHAR buf[2048], *mem = buf;
2475 int written, resize = sizeof(buf) / sizeof(WCHAR), retval;
2476 /* See vfprintf comments */
2477 while ((written = _vsnwprintf(mem, resize, format, valist)) == -1 ||
2480 resize = (written == -1 ? resize * 2 : written + sizeof(WCHAR));
2483 if (!(mem = (WCHAR *)MSVCRT_malloc(resize*sizeof(*mem))))
2486 retval = MSVCRT_fwrite(mem, sizeof(*mem), written, file);
2492 /*********************************************************************
2493 * vprintf (MSVCRT.@)
2495 int MSVCRT_vprintf(const char *format, va_list valist)
2497 return MSVCRT_vfprintf(MSVCRT_stdout,format,valist);
2500 /*********************************************************************
2501 * vwprintf (MSVCRT.@)
2503 int MSVCRT_vwprintf(const WCHAR *format, va_list valist)
2505 return MSVCRT_vfwprintf(MSVCRT_stdout,format,valist);
2508 /*********************************************************************
2509 * fprintf (MSVCRT.@)
2511 int MSVCRT_fprintf(MSVCRT_FILE* file, const char *format, ...)
2515 va_start(valist, format);
2516 res = MSVCRT_vfprintf(file, format, valist);
2521 /*********************************************************************
2522 * fwprintf (MSVCRT.@)
2524 int MSVCRT_fwprintf(MSVCRT_FILE* file, const WCHAR *format, ...)
2528 va_start(valist, format);
2529 res = MSVCRT_vfwprintf(file, format, valist);
2534 /*********************************************************************
2537 int MSVCRT_printf(const char *format, ...)
2541 va_start(valist, format);
2542 res = MSVCRT_vfprintf(MSVCRT_stdout, format, valist);
2547 /*********************************************************************
2550 int MSVCRT_ungetc(int c, MSVCRT_FILE * file)
2552 if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
2553 msvcrt_alloc_buffer(file);
2556 if(file->_ptr>file->_base) {
2565 /*********************************************************************
2566 * ungetwc (MSVCRT.@)
2568 MSVCRT_wint_t MSVCRT_ungetwc(MSVCRT_wint_t wc, MSVCRT_FILE * file)
2571 char * pp = (char *)&mwc;
2573 for(i=sizeof(WCHAR)-1;i>=0;i--) {
2574 if(pp[i] != MSVCRT_ungetc(pp[i],file))
2580 /*********************************************************************
2581 * wprintf (MSVCRT.@)
2583 int MSVCRT_wprintf(const WCHAR *format, ...)
2587 va_start(valist, format);
2588 res = MSVCRT_vwprintf(format, valist);