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);
105 SET_THREAD_VAR(doserrno,0);
106 SET_THREAD_VAR(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);
163 SET_THREAD_VAR(doserrno,0);
164 SET_THREAD_VAR(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 /* INTERNAL: Flush stdio file buffer */
206 static int msvcrt_flush_buffer(MSVCRT_FILE* file)
209 int cnt=file->_ptr-file->_base;
210 if(cnt>0 && _write(file->_file, file->_base, cnt) != cnt) {
213 file->_ptr=file->_base;
214 file->_cnt=file->_bufsiz;
219 /* INTERNAL: Allocate stdio file buffer */
220 static void msvcrt_alloc_buffer(MSVCRT_FILE* file)
222 file->_base = MSVCRT_calloc(MSVCRT_BUFSIZ,1);
224 file->_bufsiz = MSVCRT_BUFSIZ;
225 file->_flag |= MSVCRT__IOMYBUF;
227 file->_base = (unsigned char *)(&file->_charbuf);
229 file->_bufsiz = sizeof(file->_charbuf);
231 file->_ptr = file->_base;
235 /*********************************************************************
238 MSVCRT_FILE *__p__iob(void)
240 return &MSVCRT__iob[0];
243 /*********************************************************************
246 int _access(const char *filename, int mode)
248 DWORD attr = GetFileAttributesA(filename);
250 TRACE("(%s,%d) %ld\n",filename,mode,attr);
252 if (!filename || attr == 0xffffffff)
254 MSVCRT__set_errno(GetLastError());
257 if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
259 MSVCRT__set_errno(ERROR_ACCESS_DENIED);
265 /*********************************************************************
266 * _waccess (MSVCRT.@)
268 int _waccess(const WCHAR *filename, int mode)
270 DWORD attr = GetFileAttributesW(filename);
272 TRACE("(%s,%d) %ld\n",debugstr_w(filename),mode,attr);
274 if (!filename || attr == 0xffffffff)
276 MSVCRT__set_errno(GetLastError());
279 if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
281 MSVCRT__set_errno(ERROR_ACCESS_DENIED);
287 /*********************************************************************
290 int _chmod(const char *path, int flags)
292 DWORD oldFlags = GetFileAttributesA(path);
294 if (oldFlags != 0x0FFFFFFFF)
296 DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
297 oldFlags | FILE_ATTRIBUTE_READONLY;
299 if (newFlags == oldFlags || SetFileAttributesA(path, newFlags))
302 MSVCRT__set_errno(GetLastError());
306 /*********************************************************************
309 int _wchmod(const WCHAR *path, int flags)
311 DWORD oldFlags = GetFileAttributesW(path);
313 if (oldFlags != 0x0FFFFFFFF)
315 DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
316 oldFlags | FILE_ATTRIBUTE_READONLY;
318 if (newFlags == oldFlags || SetFileAttributesW(path, newFlags))
321 MSVCRT__set_errno(GetLastError());
325 /*********************************************************************
328 int _unlink(const char *path)
330 TRACE("(%s)\n",path);
331 if(DeleteFileA(path))
333 TRACE("failed (%ld)\n",GetLastError());
334 MSVCRT__set_errno(GetLastError());
338 /*********************************************************************
339 * _wunlink (MSVCRT.@)
341 int _wunlink(const WCHAR *path)
343 TRACE("(%s)\n",debugstr_w(path));
344 if(DeleteFileW(path))
346 TRACE("failed (%ld)\n",GetLastError());
347 MSVCRT__set_errno(GetLastError());
351 /*********************************************************************
356 HANDLE hand = msvcrt_fdtoh(fd);
358 TRACE(":fd (%d) handle (%d)\n",fd,hand);
359 if (hand == INVALID_HANDLE_VALUE)
361 /* flush stdio buffers */
362 if(MSVCRT_files[fd]) {
363 if(MSVCRT_files[fd]->_flag & MSVCRT__IOWRT)
364 MSVCRT_fflush(MSVCRT_files[fd]);
366 if(MSVCRT_files[fd]->_flag & MSVCRT__IOMYBUF)
367 MSVCRT_free(MSVCRT_files[fd]->_base);
370 /* Dont free std FILE*'s, they are not dynamic */
371 if (fd > 2 && MSVCRT_files[fd])
372 MSVCRT_free(MSVCRT_files[fd]);
376 if (!CloseHandle(hand))
378 WARN(":failed-last error (%ld)\n",GetLastError());
379 MSVCRT__set_errno(GetLastError());
382 if (MSVCRT_tempfiles[fd])
384 TRACE("deleting temporary file '%s'\n",MSVCRT_tempfiles[fd]);
385 _unlink(MSVCRT_tempfiles[fd]);
386 MSVCRT_free(MSVCRT_tempfiles[fd]);
387 MSVCRT_tempfiles[fd] = NULL;
394 /*********************************************************************
399 HANDLE hand = msvcrt_fdtoh(fd);
401 TRACE(":fd (%d) handle (%d)\n",fd,hand);
402 if (hand == INVALID_HANDLE_VALUE)
405 if (!FlushFileBuffers(hand))
407 if (GetLastError() == ERROR_INVALID_HANDLE)
409 /* FlushFileBuffers fails for console handles
410 * so we ignore this error.
414 TRACE(":failed-last error (%ld)\n",GetLastError());
415 MSVCRT__set_errno(GetLastError());
422 /*********************************************************************
428 HANDLE hand = msvcrt_fdtoh(fd);
430 TRACE(":fd (%d) handle (%d)\n",fd,hand);
432 if (hand == INVALID_HANDLE_VALUE)
435 /* If we have a FILE* for this file, the EOF flag
436 * will be set by the read()/write() functions.
438 if (MSVCRT_files[fd])
439 return MSVCRT_flags[fd] & MSVCRT__IOEOF;
441 /* Otherwise we do it the hard way */
442 curpos = SetFilePointer(hand, 0, NULL, SEEK_CUR);
443 endpos = SetFilePointer(hand, 0, NULL, FILE_END);
445 if (curpos == endpos)
448 SetFilePointer(hand, curpos, 0, FILE_BEGIN);
452 /*********************************************************************
453 * _fcloseall (MSVCRT.@)
457 int num_closed = 0, i;
459 for (i = 3; i < MSVCRT_fdend; i++)
460 if (MSVCRT_handles[i] != INVALID_HANDLE_VALUE)
466 TRACE(":closed (%d) handles\n",num_closed);
470 /*********************************************************************
473 LONG _lseek(int fd, LONG offset, int whence)
476 HANDLE hand = msvcrt_fdtoh(fd);
478 TRACE(":fd (%d) handle (%d)\n",fd,hand);
479 if (hand == INVALID_HANDLE_VALUE)
482 if (whence < 0 || whence > 2)
484 SET_THREAD_VAR(errno,MSVCRT_EINVAL);
488 TRACE(":fd (%d) to 0x%08lx pos %s\n",
489 fd,offset,(whence==SEEK_SET)?"SEEK_SET":
490 (whence==SEEK_CUR)?"SEEK_CUR":
491 (whence==SEEK_END)?"SEEK_END":"UNKNOWN");
493 if ((ret = SetFilePointer(hand, offset, NULL, whence)) != 0xffffffff)
495 if (MSVCRT_files[fd])
496 MSVCRT_files[fd]->_flag &= ~MSVCRT__IOEOF;
497 /* FIXME: What if we seek _to_ EOF - is EOF set? */
500 TRACE(":error-last error (%ld)\n",GetLastError());
501 if (MSVCRT_files[fd])
502 switch(GetLastError())
504 case ERROR_NEGATIVE_SEEK:
505 case ERROR_SEEK_ON_DEVICE:
506 MSVCRT__set_errno(GetLastError());
507 MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
515 /*********************************************************************
516 * _locking (MSVCRT.@)
518 * This is untested; the underlying LockFile doesn't work yet.
520 int _locking(int fd, int mode, LONG nbytes)
524 HANDLE hand = msvcrt_fdtoh(fd);
526 TRACE(":fd (%d) handle (%d)\n",fd,hand);
527 if (hand == INVALID_HANDLE_VALUE)
530 if (mode < 0 || mode > 4)
532 SET_THREAD_VAR(errno,MSVCRT_EINVAL);
536 TRACE(":fd (%d) by 0x%08lx mode %s\n",
537 fd,nbytes,(mode==_LK_UNLCK)?"_LK_UNLCK":
538 (mode==_LK_LOCK)?"_LK_LOCK":
539 (mode==_LK_NBLCK)?"_LK_NBLCK":
540 (mode==_LK_RLCK)?"_LK_RLCK":
541 (mode==_LK_NBRLCK)?"_LK_NBRLCK":
544 if ((cur_locn = SetFilePointer(hand, 0L, NULL, SEEK_CUR)) == 0xffffffff)
546 FIXME ("Seek failed\n");
547 SET_THREAD_VAR(errno,MSVCRT_EINVAL); /* FIXME */
550 if (mode == _LK_LOCK || mode == _LK_RLCK)
553 ret = 1; /* just to satisfy gcc */
556 ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
561 else if (mode == _LK_UNLCK)
562 ret = UnlockFile(hand, cur_locn, 0L, nbytes, 0L);
564 ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
565 /* FIXME - what about error settings? */
569 /*********************************************************************
572 void MSVCRT_rewind(MSVCRT_FILE* file)
574 TRACE(":file (%p) fd (%d)\n",file,file->_file);
575 MSVCRT_fseek(file, 0L, SEEK_SET);
576 MSVCRT_clearerr(file);
579 /*********************************************************************
582 MSVCRT_FILE* _fdopen(int fd, const char *mode)
584 MSVCRT_FILE* file = msvcrt_alloc_fp(fd);
586 TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,mode,file);
593 /*********************************************************************
594 * _wfdopen (MSVCRT.@)
596 MSVCRT_FILE* _wfdopen(int fd, const WCHAR *mode)
598 MSVCRT_FILE* file = msvcrt_alloc_fp(fd);
600 TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,debugstr_w(mode),file);
607 /*********************************************************************
608 * _filelength (MSVCRT.@)
610 LONG _filelength(int fd)
612 LONG curPos = _lseek(fd, 0, SEEK_CUR);
615 LONG endPos = _lseek(fd, 0, SEEK_END);
618 if (endPos != curPos)
619 _lseek(fd, curPos, SEEK_SET);
626 /*********************************************************************
629 int _fileno(MSVCRT_FILE* file)
631 TRACE(":FILE* (%p) fd (%d)\n",file,file->_file);
635 /*********************************************************************
636 * _flushall (MSVCRT.@)
640 int num_flushed = 0, i = 3;
642 while(i < MSVCRT_fdend)
643 if (MSVCRT_handles[i] != INVALID_HANDLE_VALUE)
646 /* FIXME: flush, do not commit */
647 if (_commit(i) == -1)
649 MSVCRT_files[i]->_flag |= MSVCRT__IOERR;
651 if(MSVCRT_files[i] && MSVCRT_files[i]->_flag & MSVCRT__IOWRT) {
652 MSVCRT_fflush(MSVCRT_files[i]);
657 TRACE(":flushed (%d) handles\n",num_flushed);
661 /*********************************************************************
664 int _fstat(int fd, struct _stat* buf)
667 BY_HANDLE_FILE_INFORMATION hfi;
668 HANDLE hand = msvcrt_fdtoh(fd);
670 TRACE(":fd (%d) stat (%p)\n",fd,buf);
671 if (hand == INVALID_HANDLE_VALUE)
676 WARN(":failed-NULL buf\n");
677 MSVCRT__set_errno(ERROR_INVALID_PARAMETER);
681 memset(&hfi, 0, sizeof(hfi));
682 memset(buf, 0, sizeof(struct _stat));
683 if (!GetFileInformationByHandle(hand, &hfi))
685 WARN(":failed-last error (%ld)\n",GetLastError());
686 MSVCRT__set_errno(ERROR_INVALID_PARAMETER);
689 FIXME(":dwFileAttributes = %ld, mode set to 0\n",hfi.dwFileAttributes);
690 buf->st_nlink = hfi.nNumberOfLinks;
691 buf->st_size = hfi.nFileSizeLow;
692 RtlTimeToSecondsSince1970(&hfi.ftLastAccessTime, &dw);
694 RtlTimeToSecondsSince1970(&hfi.ftLastWriteTime, &dw);
695 buf->st_mtime = buf->st_ctime = dw;
699 /*********************************************************************
702 int _futime(int fd, struct _utimbuf *t)
704 HANDLE hand = msvcrt_fdtoh(fd);
709 MSVCRT_time_t currTime;
710 MSVCRT_time(&currTime);
711 RtlSecondsSince1970ToTime(currTime, &at);
712 memcpy(&wt, &at, sizeof(wt));
716 RtlSecondsSince1970ToTime(t->actime, &at);
717 if (t->actime == t->modtime)
718 memcpy(&wt, &at, sizeof(wt));
720 RtlSecondsSince1970ToTime(t->modtime, &wt);
723 if (!SetFileTime(hand, NULL, &at, &wt))
725 MSVCRT__set_errno(GetLastError());
731 /*********************************************************************
732 * _get_osfhandle (MSVCRT.@)
734 long _get_osfhandle(int fd)
736 HANDLE hand = msvcrt_fdtoh(fd);
737 HANDLE newhand = hand;
738 TRACE(":fd (%d) handle (%d)\n",fd,hand);
740 if (hand != INVALID_HANDLE_VALUE)
742 /* FIXME: I'm not convinced that I should be copying the
743 * handle here - it may be leaked if the app doesn't
744 * close it (and the API docs dont say that it should)
745 * Not duplicating it means that it can't be inherited
746 * and so lcc's wedit doesn't cope when it passes it to
747 * child processes. I've an idea that it should either
748 * be copied by CreateProcess, or marked as inheritable
749 * when initialised, or maybe both? JG 21-9-00.
751 DuplicateHandle(GetCurrentProcess(),hand,GetCurrentProcess(),
752 &newhand,0,TRUE,DUPLICATE_SAME_ACCESS);
757 /*********************************************************************
762 HANDLE hand = msvcrt_fdtoh(fd);
764 TRACE(":fd (%d) handle (%d)\n",fd,hand);
765 if (hand == INVALID_HANDLE_VALUE)
768 return GetFileType(hand) == FILE_TYPE_CHAR? 1 : 0;
771 /*********************************************************************
774 char *_mktemp(char *pattern)
777 char *retVal = pattern;
782 numX = (*pattern++ == 'X')? numX + 1 : 0;
786 id = GetCurrentProcessId();
790 int tempNum = id / 10;
791 *pattern-- = id - (tempNum * 10) + '0';
797 if (GetFileAttributesA(retVal) == 0xFFFFFFFF &&
798 GetLastError() == ERROR_FILE_NOT_FOUND)
801 } while(letter != '|');
805 /*********************************************************************
806 * _wmktemp (MSVCRT.@)
808 WCHAR *_wmktemp(WCHAR *pattern)
811 WCHAR *retVal = pattern;
813 WCHAR letter = (WCHAR)L'a';
816 numX = (*pattern++ == (WCHAR)L'X')? numX + 1 : 0;
820 id = GetCurrentProcessId();
824 int tempNum = id / 10;
825 *pattern-- = id - (tempNum * 10) + (WCHAR)L'0';
831 if (GetFileAttributesW(retVal) == 0xFFFFFFFF &&
832 GetLastError() == ERROR_FILE_NOT_FOUND)
835 } while(letter != (WCHAR)L'|');
839 /*********************************************************************
842 int MSVCRT__sopen( const char *path, int oflags, int shflags, ... )
846 DWORD access = 0, creation = 0;
850 SECURITY_ATTRIBUTES sa;
853 TRACE(":file (%s) oflags: 0x%04x shflags: 0x%04x\n",
854 path, oflags, shflags);
856 switch(oflags & (_O_RDONLY | _O_WRONLY | _O_RDWR))
859 access |= GENERIC_READ;
860 ioflag |= MSVCRT__IOREAD;
863 access |= GENERIC_WRITE;
864 ioflag |= MSVCRT__IOWRT;
867 access |= GENERIC_WRITE | GENERIC_READ;
868 ioflag |= MSVCRT__IORW;
872 if (oflags & _O_CREAT)
874 va_start(ap, shflags);
875 pmode = va_arg(ap, int);
878 FIXME(": pmode 0x%04x ignored\n", pmode);
880 if (oflags & _O_EXCL)
881 creation = CREATE_NEW;
882 else if (oflags & _O_TRUNC)
883 creation = CREATE_ALWAYS;
885 creation = OPEN_ALWAYS;
887 else /* no _O_CREAT */
889 if (oflags & _O_TRUNC)
890 creation = TRUNCATE_EXISTING;
892 creation = OPEN_EXISTING;
894 if (oflags & _O_APPEND)
895 ioflag |= MSVCRT__IOAPPEND;
898 oflags |= _O_BINARY; /* FIXME: Default to text */
900 if (oflags & _O_TEXT)
902 /* Dont warn when writing */
903 if (ioflag & GENERIC_READ)
904 FIXME(":TEXT node not implemented\n");
914 sharing = FILE_SHARE_READ;
917 sharing = FILE_SHARE_WRITE;
920 sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
923 ERR( "Unhandled shflags 0x%x\n", shflags );
927 if (oflags & ~(_O_BINARY|_O_TEXT|_O_APPEND|_O_TRUNC|_O_EXCL
928 |_O_CREAT|_O_RDWR|_O_TEMPORARY|_O_NOINHERIT))
929 TRACE(":unsupported oflags 0x%04x\n",oflags);
931 sa.nLength = sizeof( SECURITY_ATTRIBUTES );
932 sa.lpSecurityDescriptor = NULL;
933 sa.bInheritHandle = (oflags & _O_NOINHERIT) ? FALSE : TRUE;
935 hand = CreateFileA(path, access, sharing,
936 &sa, creation, FILE_ATTRIBUTE_NORMAL, 0);
938 if (hand == INVALID_HANDLE_VALUE) {
939 WARN(":failed-last error (%ld)\n",GetLastError());
940 MSVCRT__set_errno(GetLastError());
944 fd = msvcrt_alloc_fd(hand, ioflag);
946 TRACE(":fd (%d) handle (%d)\n",fd, hand);
950 if (oflags & _O_TEMPORARY)
951 MSVCRT_tempfiles[fd] = _strdup(path);
952 if (ioflag & MSVCRT__IOAPPEND)
953 _lseek(fd, 0, FILE_END);
959 /*********************************************************************
962 int MSVCRT__wsopen( const WCHAR* path, int oflags, int shflags, ... )
964 const unsigned int len = strlenW(path);
965 char *patha = MSVCRT_calloc(len + 1,1);
969 va_start(ap, shflags);
970 pmode = va_arg(ap, int);
973 if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
975 int retval = MSVCRT__sopen(patha,oflags,shflags,pmode);
980 MSVCRT__set_errno(GetLastError());
984 /*********************************************************************
987 int _open( const char *path, int flags, ... )
993 pmode = va_arg(ap, int);
996 return MSVCRT__sopen( path, flags, _SH_DENYNO, pmode );
999 /*********************************************************************
1002 int _wopen(const WCHAR *path,int flags,...)
1004 const unsigned int len = strlenW(path);
1005 char *patha = MSVCRT_calloc(len + 1,1);
1009 va_start(ap, flags);
1010 pmode = va_arg(ap, int);
1013 if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
1015 int retval = _open(patha,flags,pmode);
1020 MSVCRT__set_errno(GetLastError());
1024 /*********************************************************************
1027 int _creat(const char *path, int flags)
1029 int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
1030 return _open(path, usedFlags);
1033 /*********************************************************************
1034 * _wcreat (MSVCRT.@)
1036 int _wcreat(const WCHAR *path, int flags)
1038 int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
1039 return _wopen(path, usedFlags);
1042 /*********************************************************************
1043 * _open_osfhandle (MSVCRT.@)
1045 int _open_osfhandle(long hand, int flags)
1047 int fd = msvcrt_alloc_fd(hand,flags);
1048 TRACE(":handle (%ld) fd (%d)\n",hand,fd);
1052 /*********************************************************************
1057 int num_removed = 0, i;
1059 for (i = 3; i < MSVCRT_fdend; i++)
1060 if (MSVCRT_tempfiles[i])
1067 TRACE(":removed (%d) temp files\n",num_removed);
1071 /*********************************************************************
1074 int _read(int fd, void *buf, unsigned int count)
1077 HANDLE hand = msvcrt_fdtoh(fd);
1079 /* Dont trace small reads, it gets *very* annoying */
1081 TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
1082 if (hand == INVALID_HANDLE_VALUE)
1085 if (ReadFile(hand, buf, count, &num_read, NULL))
1087 if (num_read != count && MSVCRT_files[fd])
1090 MSVCRT_flags[fd] |= MSVCRT__IOEOF;
1092 MSVCRT_files[fd]->_flag |= MSVCRT__IOEOF;
1097 TRACE(":failed-last error (%ld)\n",GetLastError());
1098 if (MSVCRT_files[fd])
1099 MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
1103 /*********************************************************************
1106 int _getw(MSVCRT_FILE* file)
1109 if (_read(file->_file, &i, sizeof(int)) != 1)
1114 /*********************************************************************
1115 * _setmode (MSVCRT.@)
1117 int _setmode(int fd,int mode)
1120 FIXME("fd (%d) mode (%d) TEXT not implemented\n",fd,mode);
1124 /*********************************************************************
1127 int _stat(const char* path, struct _stat * buf)
1130 WIN32_FILE_ATTRIBUTE_DATA hfi;
1131 unsigned short mode = MSVCRT_S_IREAD;
1134 TRACE(":file (%s) buf(%p)\n",path,buf);
1136 if (!GetFileAttributesExA(path, GetFileExInfoStandard, &hfi))
1138 TRACE("failed (%ld)\n",GetLastError());
1139 MSVCRT__set_errno(ERROR_FILE_NOT_FOUND);
1143 memset(buf,0,sizeof(struct _stat));
1145 /* FIXME: rdev isnt drive num,despite what the docs say-what is it?
1146 Bon 011120: This FIXME seems incorrect
1147 Also a letter as first char isn't enough to be classify
1150 if (isalpha(*path)&& (*(path+1)==':'))
1151 buf->st_dev = buf->st_rdev = toupper(*path) - 'A'; /* drive num */
1153 buf->st_dev = buf->st_rdev = _getdrive() - 1;
1155 plen = strlen(path);
1157 /* Dir, or regular file? */
1158 if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1159 (path[plen-1] == '\\'))
1160 mode |= (_S_IFDIR | MSVCRT_S_IEXEC);
1165 if (plen > 6 && path[plen-4] == '.') /* shortest exe: "\x.exe" */
1167 unsigned int ext = tolower(path[plen-1]) | (tolower(path[plen-2]) << 8) |
1168 (tolower(path[plen-3]) << 16);
1169 if (ext == EXE || ext == BAT || ext == CMD || ext == COM)
1170 mode |= MSVCRT_S_IEXEC;
1174 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1175 mode |= MSVCRT_S_IWRITE;
1177 buf->st_mode = mode;
1179 buf->st_size = hfi.nFileSizeLow;
1180 RtlTimeToSecondsSince1970(&hfi.ftLastAccessTime, &dw);
1182 RtlTimeToSecondsSince1970(&hfi.ftLastWriteTime, &dw);
1183 buf->st_mtime = buf->st_ctime = dw;
1184 TRACE("\n%d %d %d %ld %ld %ld\n", buf->st_mode,buf->st_nlink,buf->st_size,
1185 buf->st_atime,buf->st_mtime, buf->st_ctime);
1189 /*********************************************************************
1192 int _wstat(const WCHAR* path, struct _stat * buf)
1195 WIN32_FILE_ATTRIBUTE_DATA hfi;
1196 unsigned short mode = MSVCRT_S_IREAD;
1199 TRACE(":file (%s) buf(%p)\n",debugstr_w(path),buf);
1201 if (!GetFileAttributesExW(path, GetFileExInfoStandard, &hfi))
1203 TRACE("failed (%ld)\n",GetLastError());
1204 MSVCRT__set_errno(ERROR_FILE_NOT_FOUND);
1208 memset(buf,0,sizeof(struct _stat));
1210 /* FIXME: rdev isn't drive num, despite what the docs says-what is it? */
1211 if (MSVCRT_iswalpha(*path))
1212 buf->st_dev = buf->st_rdev = toupperW(*path - (WCHAR)L'A'); /* drive num */
1214 buf->st_dev = buf->st_rdev = _getdrive() - 1;
1216 plen = strlenW(path);
1218 /* Dir, or regular file? */
1219 if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1220 (path[plen-1] == (WCHAR)L'\\'))
1221 mode |= (_S_IFDIR | MSVCRT_S_IEXEC);
1226 if (plen > 6 && path[plen-4] == (WCHAR)L'.') /* shortest exe: "\x.exe" */
1228 ULONGLONG ext = tolowerW(path[plen-1]) | (tolowerW(path[plen-2]) << 16) |
1229 ((ULONGLONG)tolowerW(path[plen-3]) << 32);
1230 if (ext == WCEXE || ext == WCBAT || ext == WCCMD || ext == WCCOM)
1231 mode |= MSVCRT_S_IEXEC;
1235 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1236 mode |= MSVCRT_S_IWRITE;
1238 buf->st_mode = mode;
1240 buf->st_size = hfi.nFileSizeLow;
1241 RtlTimeToSecondsSince1970(&hfi.ftLastAccessTime, &dw);
1243 RtlTimeToSecondsSince1970(&hfi.ftLastWriteTime, &dw);
1244 buf->st_mtime = buf->st_ctime = dw;
1245 TRACE("\n%d %d %d %ld %ld %ld\n", buf->st_mode,buf->st_nlink,buf->st_size,
1246 buf->st_atime,buf->st_mtime, buf->st_ctime);
1250 /*********************************************************************
1255 return _lseek(fd, 0, SEEK_CUR);
1258 /*********************************************************************
1259 * _tempnam (MSVCRT.@)
1261 char *_tempnam(const char *dir, const char *prefix)
1263 char tmpbuf[MAX_PATH];
1265 TRACE("dir (%s) prefix (%s)\n",dir,prefix);
1266 if (GetTempFileNameA(dir,prefix,0,tmpbuf))
1268 TRACE("got name (%s)\n",tmpbuf);
1269 return _strdup(tmpbuf);
1271 TRACE("failed (%ld)\n",GetLastError());
1275 /*********************************************************************
1276 * _wtempnam (MSVCRT.@)
1278 WCHAR *_wtempnam(const WCHAR *dir, const WCHAR *prefix)
1280 WCHAR tmpbuf[MAX_PATH];
1282 TRACE("dir (%s) prefix (%s)\n",debugstr_w(dir),debugstr_w(prefix));
1283 if (GetTempFileNameW(dir,prefix,0,tmpbuf))
1285 TRACE("got name (%s)\n",debugstr_w(tmpbuf));
1286 return _wcsdup(tmpbuf);
1288 TRACE("failed (%ld)\n",GetLastError());
1292 /*********************************************************************
1295 int _umask(int umask)
1297 int old_umask = MSVCRT_umask;
1298 TRACE("(%d)\n",umask);
1299 MSVCRT_umask = umask;
1303 /*********************************************************************
1306 int _utime(const char* path, struct _utimbuf *t)
1308 int fd = _open(path, _O_WRONLY | _O_BINARY);
1312 int retVal = _futime(fd, t);
1319 /*********************************************************************
1320 * _wutime (MSVCRT.@)
1322 int _wutime(const WCHAR* path, struct _utimbuf *t)
1324 int fd = _wopen(path, _O_WRONLY | _O_BINARY);
1328 int retVal = _futime(fd, t);
1335 /*********************************************************************
1338 int _write(int fd, const void* buf, unsigned int count)
1341 HANDLE hand = msvcrt_fdtoh(fd);
1343 /* Dont trace small writes, it gets *very* annoying */
1346 TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
1348 if (hand == INVALID_HANDLE_VALUE)
1351 /* If appending, go to EOF */
1352 if (MSVCRT_flags[fd] & MSVCRT__IOAPPEND)
1353 _lseek(fd, 0, FILE_END);
1355 if (WriteFile(hand, buf, count, &num_written, NULL)
1356 && (num_written == count))
1359 TRACE(":failed-last error (%ld)\n",GetLastError());
1360 if (MSVCRT_files[fd])
1361 MSVCRT_files[fd]->_flag |= MSVCRT__IOERR;
1366 /*********************************************************************
1369 int _putw(int val, MSVCRT_FILE* file)
1371 return _write(file->_file, &val, sizeof(val)) == 1? val : MSVCRT_EOF;
1374 /*********************************************************************
1375 * clearerr (MSVCRT.@)
1377 void MSVCRT_clearerr(MSVCRT_FILE* file)
1379 TRACE(":file (%p) fd (%d)\n",file,file->_file);
1380 file->_flag &= ~(MSVCRT__IOERR | MSVCRT__IOEOF);
1383 /*********************************************************************
1386 int MSVCRT_fclose(MSVCRT_FILE* file)
1389 r=_close(file->_file);
1390 return ((r==MSVCRT_EOF) || (file->_flag & MSVCRT__IOERR) ? MSVCRT_EOF : 0);
1393 /*********************************************************************
1396 int MSVCRT_feof(MSVCRT_FILE* file)
1398 return file->_flag & MSVCRT__IOEOF;
1401 /*********************************************************************
1404 int MSVCRT_ferror(MSVCRT_FILE* file)
1406 return file->_flag & MSVCRT__IOERR;
1409 /*********************************************************************
1412 int MSVCRT_fflush(MSVCRT_FILE* file)
1418 int res=msvcrt_flush_buffer(file);
1423 /*********************************************************************
1426 int MSVCRT_fgetc(MSVCRT_FILE* file)
1430 return *(unsigned char *)file->_ptr++;
1432 return _filbuf(file);
1436 /*********************************************************************
1437 * _fgetchar (MSVCRT.@)
1441 return MSVCRT_fgetc(MSVCRT_stdin);
1444 /*********************************************************************
1445 * _filbuf (MSVCRT.@)
1447 int _filbuf(MSVCRT_FILE* file)
1450 /* Allocate buffer if needed */
1451 if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF) ) {
1452 msvcrt_alloc_buffer(file);
1454 if(!(file->_flag & MSVCRT__IOREAD)) {
1455 if(file->_flag & MSVCRT__IORW) {
1456 file->_flag |= MSVCRT__IOREAD;
1461 if(file->_flag & MSVCRT__IONBF) {
1463 if (_read(file->_file,&c,1) != 1) {
1464 file->_flag |= MSVCRT__IOEOF;
1469 file->_cnt = _read(file->_file, file->_base, file->_bufsiz);
1470 if(file->_cnt<0) file->_cnt = 0;
1472 file->_flag |= MSVCRT__IOEOF;
1476 file->_ptr = file->_base+1;
1477 return *(unsigned char *)file->_base;
1481 /*********************************************************************
1482 * fgetpos (MSVCRT.@)
1484 int MSVCRT_fgetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
1486 *pos = MSVCRT_ftell(file);
1487 return (*pos == -1? -1 : 0);
1490 /*********************************************************************
1493 char *MSVCRT_fgets(char *s, int size, MSVCRT_FILE* file)
1496 char * buf_start = s;
1498 TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
1499 file,file->_file,s,size);
1501 for(cc = MSVCRT_fgetc(file); cc != MSVCRT_EOF && cc != '\n';
1502 cc = MSVCRT_fgetc(file))
1505 if (--size <= 0) break;
1508 if ((cc == MSVCRT_EOF) && (s == buf_start)) /* If nothing read, return 0*/
1510 TRACE(":nothing read\n");
1517 TRACE(":got '%s'\n", buf_start);
1521 /*********************************************************************
1524 MSVCRT_wint_t MSVCRT_fgetwc(MSVCRT_FILE* file)
1527 if (_read(file->_file, &wc, sizeof(wc)) != sizeof(wc))
1532 /*********************************************************************
1535 MSVCRT_wint_t MSVCRT_getwc(MSVCRT_FILE* file)
1537 return MSVCRT_fgetwc(file);
1540 /*********************************************************************
1541 * _fgetwchar (MSVCRT.@)
1543 MSVCRT_wint_t _fgetwchar(void)
1545 return MSVCRT_fgetwc(MSVCRT_stdin);
1548 /*********************************************************************
1549 * getwchar (MSVCRT.@)
1551 MSVCRT_wint_t MSVCRT_getwchar(void)
1553 return _fgetwchar();
1556 /*********************************************************************
1559 WCHAR *MSVCRT_fgetws(WCHAR *s, int size, MSVCRT_FILE* file)
1562 WCHAR * buf_start = s;
1564 TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
1565 file,file->_file,s,size);
1567 for(cc = MSVCRT_fgetwc(file); cc != MSVCRT_WEOF && cc != L'\n';
1568 cc = MSVCRT_fgetwc(file))
1571 if (--size <= 0) break;
1574 if ((cc == MSVCRT_EOF) && (s == buf_start)) /* If nothing read, return 0*/
1576 TRACE(":nothing read\n");
1583 /* TRACE(":got '%s'\n", buf_start); */
1588 /*********************************************************************
1591 MSVCRT_wint_t MSVCRT_fputwc(MSVCRT_wint_t wc, MSVCRT_FILE* file)
1594 if (MSVCRT_fwrite( &mwc, sizeof(mwc), 1, file) != 1)
1599 /*********************************************************************
1600 * _fputwchar (MSVCRT.@)
1602 MSVCRT_wint_t _fputwchar(MSVCRT_wint_t wc)
1604 return MSVCRT_fputwc(wc, MSVCRT_stdout);
1607 /*********************************************************************
1610 MSVCRT_FILE* MSVCRT_fopen(const char *path, const char *mode)
1613 int flags = 0, plus = 0, fd;
1614 const char* search = mode;
1616 TRACE("(%s,%s)\n",path,mode);
1619 if (*search++ == '+')
1622 /* map mode string to open() flags. "man fopen" for possibilities. */
1626 flags = (plus ? _O_RDWR : _O_RDONLY);
1629 flags = _O_CREAT | _O_TRUNC | (plus ? _O_RDWR : _O_WRONLY);
1632 flags = _O_CREAT | _O_APPEND | (plus ? _O_RDWR : _O_WRONLY);
1647 flags &= ~_O_BINARY;
1652 FIXME(":unknown flag %c not supported\n",mode[-1]);
1655 fd = _open(path, flags);
1660 file = msvcrt_alloc_fp(fd);
1661 TRACE(":got (%p)\n",file);
1668 /*********************************************************************
1669 * _wfopen (MSVCRT.@)
1671 MSVCRT_FILE *_wfopen(const WCHAR *path, const WCHAR *mode)
1673 const unsigned int plen = strlenW(path), mlen = strlenW(mode);
1674 char *patha = MSVCRT_calloc(plen + 1, 1);
1675 char *modea = MSVCRT_calloc(mlen + 1, 1);
1677 TRACE("(%s,%s)\n",debugstr_w(path),debugstr_w(mode));
1679 if (patha && modea &&
1680 WideCharToMultiByte(CP_ACP,0,path,plen,patha,plen,NULL,NULL) &&
1681 WideCharToMultiByte(CP_ACP,0,mode,mlen,modea,mlen,NULL,NULL))
1683 MSVCRT_FILE *retval = MSVCRT_fopen(patha,modea);
1689 MSVCRT__set_errno(GetLastError());
1693 /*********************************************************************
1694 * _fsopen (MSVCRT.@)
1696 MSVCRT_FILE* _fsopen(const char *path, const char *mode, int share)
1698 FIXME(":(%s,%s,%d),ignoring share mode!\n",path,mode,share);
1699 return MSVCRT_fopen(path,mode);
1702 /*********************************************************************
1703 * _wfsopen (MSVCRT.@)
1705 MSVCRT_FILE* _wfsopen(const WCHAR *path, const WCHAR *mode, int share)
1707 FIXME(":(%s,%s,%d),ignoring share mode!\n",
1708 debugstr_w(path),debugstr_w(mode),share);
1709 return _wfopen(path,mode);
1712 /*********************************************************************
1715 int MSVCRT_fputc(int c, MSVCRT_FILE* file)
1722 return _flsbuf(c, file);
1726 /*********************************************************************
1727 * _flsbuf (MSVCRT.@)
1729 int _flsbuf(int c, MSVCRT_FILE* file)
1731 /* Flush output buffer */
1732 if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
1733 msvcrt_alloc_buffer(file);
1735 if(!(file->_flag & MSVCRT__IOWRT)) {
1736 if(file->_flag & MSVCRT__IORW) {
1737 file->_flag |= MSVCRT__IOWRT;
1743 int res=msvcrt_flush_buffer(file);
1744 return res?res : MSVCRT_fputc(c, file);
1747 return _write(file->_file, &cc, 1) == 1? c : MSVCRT_EOF;
1751 /*********************************************************************
1752 * _fputchar (MSVCRT.@)
1754 int _fputchar(int c)
1756 return MSVCRT_fputc(c, MSVCRT_stdout);
1759 /*********************************************************************
1762 MSVCRT_size_t MSVCRT_fread(void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
1763 { MSVCRT_size_t rcnt=size * nmemb;
1764 MSVCRT_size_t read=0;
1766 /* first buffered data */
1768 int pcnt= (rcnt>file->_cnt)? file->_cnt:rcnt;
1769 memcpy(ptr, file->_ptr, pcnt);
1775 } else if(!(file->_flag & MSVCRT__IOREAD )) {
1776 if(file->_flag & MSVCRT__IORW) {
1777 file->_flag |= MSVCRT__IOREAD;
1781 if(rcnt) pread = _read(file->_file,ptr, rcnt);
1788 /*********************************************************************
1789 * freopen (MSVCRT.@)
1792 MSVCRT_FILE* MSVCRT_freopen(const char *path, const char *mode,MSVCRT_FILE* file)
1794 MSVCRT_FILE* newfile;
1797 TRACE(":path (%p) mode (%s) file (%p) fd (%d)\n",path,mode,file,file->_file);
1798 if (!file || ((fd = file->_file) < 0) || fd > MSVCRT_fdend)
1804 FIXME(":reopen on user file not implemented!\n");
1805 MSVCRT__set_errno(ERROR_CALL_NOT_IMPLEMENTED);
1808 if(MSVCRT_fclose(file))
1810 return MSVCRT_fopen(path, mode);
1813 /* first, create the new file */
1814 if ((newfile = MSVCRT_fopen(path,mode)) == NULL)
1817 if (fd < 3 && SetStdHandle(fd == 0 ? STD_INPUT_HANDLE :
1818 (fd == 1? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE),
1819 MSVCRT_handles[newfile->_file]))
1821 /* Redirecting std handle to file , copy over.. */
1822 MSVCRT_handles[fd] = MSVCRT_handles[newfile->_file];
1823 MSVCRT_flags[fd] = MSVCRT_flags[newfile->_file];
1824 memcpy(&MSVCRT__iob[fd], newfile, sizeof (MSVCRT_FILE));
1825 MSVCRT__iob[fd]._file = fd;
1826 /* And free up the resources allocated by fopen, but
1827 * not the HANDLE we copied. */
1828 MSVCRT_free(MSVCRT_files[fd]);
1829 msvcrt_free_fd(newfile->_file);
1830 return &MSVCRT__iob[fd];
1833 WARN(":failed-last error (%ld)\n",GetLastError());
1834 MSVCRT_fclose(newfile);
1835 MSVCRT__set_errno(GetLastError());
1839 /*********************************************************************
1840 * fsetpos (MSVCRT.@)
1842 int MSVCRT_fsetpos(MSVCRT_FILE* file, MSVCRT_fpos_t *pos)
1844 return _lseek(file->_file,*pos,SEEK_SET);
1847 /* helper function for fscanf. Returns the value of character c in the
1848 * given base, or -1 if the given character is not a digit of the base.
1850 static int char2digit(char c, int base) {
1851 if ((c>='0') && (c<='9') && (c<='0'+base-1)) return (c-'0');
1852 if (base<=10) return -1;
1853 if ((c>='A') && (c<='Z') && (c<='A'+base-11)) return (c-'A'+10);
1854 if ((c>='a') && (c<='z') && (c<='a'+base-11)) return (c-'a'+10);
1858 /*********************************************************************
1860 * Implemented based on
1861 * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/html/_crt_format_specification_fields_.2d_.scanf_and_wscanf_functions.asp
1862 * Extended by C. Scott Ananian <cananian@alumni.princeton.edu> to handle
1863 * more types of format spec.
1865 int MSVCRT_fscanf(MSVCRT_FILE* file, const char *format, ...)
1867 /* NOTE: If you extend this function, extend MSVCRT__cscanf in console.c too */
1871 if (!*format) return 0;
1872 WARN("%p (\"%s\"): semi-stub\n", file, format);
1873 nch = MSVCRT_fgetc(file);
1874 va_start(ap, format);
1876 /* a whitespace character in the format string causes scanf to read,
1877 * but not store, all consecutive white-space characters in the input
1878 * up to the next non-white-space character. One white space character
1879 * in the input matches any number (including zero) and combination of
1880 * white-space characters in the input. */
1881 if (isspace(*format)) {
1882 /* skip whitespace */
1883 while ((nch!=MSVCRT_EOF) && isspace(nch))
1884 nch = MSVCRT_fgetc(file);
1886 /* a format specification causes scanf to read and convert characters
1887 * in the input into values of a specified type. The value is assigned
1888 * to an argument in the argument list. Format specifications have
1889 * the form %[*][width][{h | l | I64 | L}]type */
1890 /* FIXME: unimplemented: h/l/I64/L modifiers and some type specs. */
1891 else if (*format == '%') {
1892 int st = 0; int suppress = 0; int width = 0;
1893 int base, number_signed;
1895 /* look for leading asterisk, which means 'suppress assignment of
1901 /* look for width specification */
1902 while (isdigit(*format)) {
1904 width+=*format++ - '0';
1906 if (width==0) width=-1; /* no width spec seen */
1908 case '%': /* read a percent symbol */
1909 if (nch!='%') break;
1910 nch = MSVCRT_fgetc(file);
1913 case 'X': /* hexadecimal integer. */
1914 base = 16; number_signed = 0;
1916 case 'o': /* octal integer */
1917 base = 8; number_signed = 0;
1919 case 'u': /* unsigned decimal integer */
1920 base = 10; number_signed = 0;
1922 case 'd': /* signed decimal integer */
1923 base = 10; number_signed = 1;
1925 case 'i': /* generic integer */
1926 base = 0; number_signed = 1;
1928 /* read an integer */
1929 int*val = suppress ? NULL : va_arg(ap, int*);
1930 int cur = 0; int negative = 0; int seendigit=0;
1931 /* skip initial whitespace */
1932 while ((nch!=MSVCRT_EOF) && isspace(nch))
1933 nch = MSVCRT_fgetc(file);
1935 if (number_signed && (nch == '-' || nch == '+')) {
1936 negative = (nch=='-');
1937 nch = MSVCRT_fgetc(file);
1938 if (width>0) width--;
1940 /* look for leading indication of base */
1941 if (width!=0 && nch == '0') {
1942 nch = MSVCRT_fgetc(file);
1943 if (width>0) width--;
1945 if (width!=0 && (nch=='x' || nch=='X')) {
1949 nch = MSVCRT_fgetc(file);
1950 if (width>0) width--;
1958 /* throw away leading zeros */
1959 while (width!=0 && nch=='0') {
1960 nch = MSVCRT_fgetc(file);
1961 if (width>0) width--;
1964 /* get first digit. Keep working copy negative, as the
1965 * range of negative numbers in two's complement notation
1966 * is one larger than the range of positive numbers. */
1967 if (width!=0 && char2digit(nch, base)!=-1) {
1968 cur = -char2digit(nch, base);
1969 nch = MSVCRT_fgetc(file);
1970 if (width>0) width--;
1973 /* read until no more digits */
1974 while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
1975 cur = cur*base + char2digit(nch, base);
1976 nch = MSVCRT_fgetc(file);
1977 if (width>0) width--;
1980 /* negate parsed number if non-negative */
1981 if (!negative) cur=-cur;
1983 if (!seendigit) break; /* not a valid number */
1985 if (!suppress) *val = cur;
1992 case 'G': { /* read a float */
1993 float*val = suppress ? NULL : va_arg(ap, float*);
1996 /* skip initial whitespace */
1997 while ((nch!=MSVCRT_EOF) && isspace(nch))
1998 nch = MSVCRT_fgetc(file);
2000 if (nch == '-' || nch == '+') {
2001 negative = (nch=='-');
2002 if (width>0) width--;
2003 if (width==0) break;
2004 nch = MSVCRT_fgetc(file);
2006 /* get first digit. */
2007 if (!isdigit(nch)) break;
2008 cur = (nch - '0') * (negative ? -1 : 1);
2009 nch = MSVCRT_fgetc(file);
2010 if (width>0) width--;
2011 /* read until no more digits */
2012 while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
2013 cur = cur*10 + (nch - '0');
2014 nch = MSVCRT_fgetc(file);
2015 if (width>0) width--;
2017 /* handle decimals */
2018 if (width!=0 && nch == '.') {
2020 nch = MSVCRT_fgetc(file);
2021 if (width>0) width--;
2022 while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
2024 cur += dec * (nch - '0');
2025 nch = MSVCRT_fgetc(file);
2026 if (width>0) width--;
2029 /* handle exponent */
2030 if (width!=0 && (nch == 'e' || nch == 'E')) {
2031 int exponent = 0, negexp = 0;
2033 nch = MSVCRT_fgetc(file);
2034 if (width>0) width--;
2035 /* possible sign on the exponent */
2036 if (width!=0 && (nch=='+' || nch=='-')) {
2037 negexp = (nch=='-');
2038 nch = MSVCRT_fgetc(file);
2039 if (width>0) width--;
2041 /* exponent digits */
2042 while (width!=0 && (nch!=MSVCRT_EOF) && isdigit(nch)) {
2044 exponent += (nch - '0');
2045 nch = MSVCRT_fgetc(file);
2046 if (width>0) width--;
2048 /* update 'cur' with this exponent. */
2049 expcnt = negexp ? .1 : 10;
2050 while (exponent!=0) {
2054 expcnt=expcnt*expcnt;
2058 if (!suppress) *val = cur;
2061 case 's': { /* read a word */
2062 char*str = suppress ? NULL : va_arg(ap, char*);
2064 /* skip initial whitespace */
2065 while ((nch!=MSVCRT_EOF) && isspace(nch))
2066 nch = MSVCRT_fgetc(file);
2067 /* read until whitespace */
2068 while (width!=0 && (nch!=MSVCRT_EOF) && !isspace(nch)) {
2069 if (!suppress) *sptr++ = nch;
2071 nch = MSVCRT_fgetc(file);
2072 if (width>0) width--;
2075 if (!suppress) *sptr = 0;
2076 TRACE("read word: %s\n", str);
2079 default: FIXME("unhandled: %%%c\n", *format);
2080 /* From spec: "if a percent sign is followed by a character
2081 * that has no meaning as a format-control character, that
2082 * character and the following characters are treated as
2083 * an ordinary sequence of characters, that is, a sequence
2084 * of characters that must match the input. For example,
2085 * to specify that a percent-sign character is to be input,
2087 * LEAVING AS-IS because we catch bugs better that way. */
2089 if (st && !suppress) rd++;
2092 /* a non-white-space character causes scanf to read, but not store,
2093 * a matching non-white-space character. */
2095 /* check for character match */
2097 nch = MSVCRT_fgetc(file);
2102 if (nch!=MSVCRT_EOF) {
2103 FIXME("need ungetch\n");
2106 TRACE("returning %d\n", rd);
2110 /*********************************************************************
2113 int MSVCRT_fseek(MSVCRT_FILE* file, long offset, int whence)
2115 /* Flush output if needed */
2116 if(file->_flag & MSVCRT__IOWRT)
2117 msvcrt_flush_buffer(file);
2119 if(whence == SEEK_CUR && file->_flag & MSVCRT__IOREAD ) {
2120 offset -= file->_cnt;
2122 /* Discard buffered input */
2124 file->_ptr = file->_base;
2125 /* Reset direction of i/o */
2126 if(file->_flag & MSVCRT__IORW) {
2127 file->_flag &= ~(MSVCRT__IOREAD|MSVCRT__IOWRT);
2129 return _lseek(file->_file,offset,whence);
2132 /*********************************************************************
2135 LONG MSVCRT_ftell(MSVCRT_FILE* file)
2140 if( file->_flag & MSVCRT__IOWRT ) {
2141 off = file->_ptr - file->_base;
2146 pos = _tell(file->_file);
2147 if(pos == -1) return pos;
2151 /*********************************************************************
2154 MSVCRT_size_t MSVCRT_fwrite(const void *ptr, MSVCRT_size_t size, MSVCRT_size_t nmemb, MSVCRT_FILE* file)
2156 MSVCRT_size_t wrcnt=size * nmemb;
2161 int pcnt=(file->_cnt>wrcnt)? wrcnt: file->_cnt;
2162 memcpy(file->_ptr, ptr, pcnt);
2168 } else if(!(file->_flag & MSVCRT__IOWRT)) {
2169 if(file->_flag & MSVCRT__IORW) {
2170 file->_flag |= MSVCRT__IOWRT;
2176 int res=msvcrt_flush_buffer(file);
2178 int pwritten = _write(file->_file, ptr, wrcnt);
2179 if (pwritten <= 0) pwritten=0;
2180 written += pwritten;
2183 return written / size;
2186 /*********************************************************************
2189 int MSVCRT_fputs(const char *s, MSVCRT_FILE* file)
2191 size_t len = strlen(s);
2192 return MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
2195 /*********************************************************************
2198 int MSVCRT_fputws(const WCHAR *s, MSVCRT_FILE* file)
2200 size_t len = strlenW(s);
2201 return MSVCRT_fwrite(s,sizeof(*s),len,file) == len ? 0 : MSVCRT_EOF;
2204 /*********************************************************************
2205 * getchar (MSVCRT.@)
2207 int MSVCRT_getchar(void)
2209 return MSVCRT_fgetc(MSVCRT_stdin);
2212 /*********************************************************************
2215 int MSVCRT_getc(MSVCRT_FILE* file)
2217 return MSVCRT_fgetc(file);
2220 /*********************************************************************
2223 char *MSVCRT_gets(char *buf)
2226 char * buf_start = buf;
2228 for(cc = MSVCRT_fgetc(MSVCRT_stdin); cc != MSVCRT_EOF && cc != '\n';
2229 cc = MSVCRT_fgetc(MSVCRT_stdin))
2230 if(cc != '\r') *buf++ = (char)cc;
2234 TRACE("got '%s'\n", buf_start);
2238 /*********************************************************************
2241 WCHAR* MSVCRT__getws(WCHAR* buf)
2246 for (cc = MSVCRT_fgetwc(MSVCRT_stdin); cc != MSVCRT_WEOF && cc != '\n';
2247 cc = MSVCRT_fgetwc(MSVCRT_stdin))
2254 TRACE("got '%s'\n", debugstr_w(ws));
2258 /*********************************************************************
2261 int MSVCRT_putc(int c, MSVCRT_FILE* file)
2263 return MSVCRT_fputc(c, file);
2266 /*********************************************************************
2267 * putchar (MSVCRT.@)
2269 int MSVCRT_putchar(int c)
2271 return MSVCRT_fputc(c, MSVCRT_stdout);
2274 /*********************************************************************
2277 int MSVCRT_puts(const char *s)
2279 size_t len = strlen(s);
2280 if (MSVCRT_fwrite(s,sizeof(*s),len,MSVCRT_stdout) != len) return MSVCRT_EOF;
2281 return MSVCRT_fwrite("\n",1,1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
2284 /*********************************************************************
2287 int _putws(const WCHAR *s)
2289 static const WCHAR nl = '\n';
2290 size_t len = strlenW(s);
2291 if (MSVCRT_fwrite(s,sizeof(*s),len,MSVCRT_stdout) != len) return MSVCRT_EOF;
2292 return MSVCRT_fwrite(&nl,sizeof(nl),1,MSVCRT_stdout) == 1 ? 0 : MSVCRT_EOF;
2295 /*********************************************************************
2298 int MSVCRT_remove(const char *path)
2300 TRACE("(%s)\n",path);
2301 if (DeleteFileA(path))
2303 TRACE(":failed (%ld)\n",GetLastError());
2304 MSVCRT__set_errno(GetLastError());
2308 /*********************************************************************
2309 * _wremove (MSVCRT.@)
2311 int _wremove(const WCHAR *path)
2313 TRACE("(%s)\n",debugstr_w(path));
2314 if (DeleteFileW(path))
2316 TRACE(":failed (%ld)\n",GetLastError());
2317 MSVCRT__set_errno(GetLastError());
2321 /*********************************************************************
2324 int MSVCRT_scanf(const char *format, ...)
2329 va_start(valist, format);
2330 res = MSVCRT_fscanf(MSVCRT_stdin, format, valist);
2335 /*********************************************************************
2338 int MSVCRT_rename(const char *oldpath,const char *newpath)
2340 TRACE(":from %s to %s\n",oldpath,newpath);
2341 if (MoveFileExA(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
2343 TRACE(":failed (%ld)\n",GetLastError());
2344 MSVCRT__set_errno(GetLastError());
2348 /*********************************************************************
2349 * _wrename (MSVCRT.@)
2351 int _wrename(const WCHAR *oldpath,const WCHAR *newpath)
2353 TRACE(":from %s to %s\n",debugstr_w(oldpath),debugstr_w(newpath));
2354 if (MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING))
2356 TRACE(":failed (%ld)\n",GetLastError());
2357 MSVCRT__set_errno(GetLastError());
2361 /*********************************************************************
2362 * setvbuf (MSVCRT.@)
2364 int MSVCRT_setvbuf(MSVCRT_FILE* file, char *buf, int mode, MSVCRT_size_t size)
2366 /* TODO: Check if file busy */
2368 MSVCRT_free(file->_base);
2372 if(mode == MSVCRT__IOFBF) {
2373 file->_flag &= ~MSVCRT__IONBF;
2374 file->_base = file->_ptr = buf;
2376 file->_bufsiz = size;
2379 file->_flag |= MSVCRT__IONBF;
2384 /*********************************************************************
2387 void MSVCRT_setbuf(MSVCRT_FILE* file, char *buf)
2389 MSVCRT_setvbuf(file, buf, buf ? MSVCRT__IOFBF : MSVCRT__IONBF, MSVCRT_BUFSIZ);
2392 /*********************************************************************
2395 char *MSVCRT_tmpnam(char *s)
2397 char tmpbuf[MAX_PATH];
2398 char* prefix = "TMP";
2399 if (!GetTempPathA(MAX_PATH,tmpbuf) ||
2400 !GetTempFileNameA(tmpbuf,prefix,0,MSVCRT_tmpname))
2402 TRACE(":failed-last error (%ld)\n",GetLastError());
2405 TRACE(":got tmpnam %s\n",MSVCRT_tmpname);
2410 /*********************************************************************
2411 * tmpfile (MSVCRT.@)
2413 MSVCRT_FILE* MSVCRT_tmpfile(void)
2415 char *filename = MSVCRT_tmpnam(NULL);
2417 fd = _open(filename, _O_CREAT | _O_BINARY | _O_RDWR | _O_TEMPORARY);
2419 return msvcrt_alloc_fp(fd);
2423 /*********************************************************************
2424 * vfprintf (MSVCRT.@)
2426 int MSVCRT_vfprintf(MSVCRT_FILE* file, const char *format, va_list valist)
2428 char buf[2048], *mem = buf;
2429 int written, resize = sizeof(buf), retval;
2430 /* There are two conventions for vsnprintf failing:
2431 * Return -1 if we truncated, or
2432 * Return the number of bytes that would have been written
2433 * The code below handles both cases
2435 while ((written = vsnprintf(mem, resize, format, valist)) == -1 ||
2438 resize = (written == -1 ? resize * 2 : written + 1);
2441 if (!(mem = (char *)MSVCRT_malloc(resize)))
2444 retval = MSVCRT_fwrite(mem, sizeof(*mem), written, file);
2450 /*********************************************************************
2451 * vfwprintf (MSVCRT.@)
2453 * Is final char included in written (then resize is too big) or not
2454 * (then we must test for equality too)?
2456 int MSVCRT_vfwprintf(MSVCRT_FILE* file, const WCHAR *format, va_list valist)
2458 WCHAR buf[2048], *mem = buf;
2459 int written, resize = sizeof(buf) / sizeof(WCHAR), retval;
2460 /* See vfprintf comments */
2461 while ((written = _vsnwprintf(mem, resize, format, valist)) == -1 ||
2464 resize = (written == -1 ? resize * 2 : written + sizeof(WCHAR));
2467 if (!(mem = (WCHAR *)MSVCRT_malloc(resize*sizeof(*mem))))
2470 retval = MSVCRT_fwrite(mem, sizeof(*mem), written, file);
2476 /*********************************************************************
2477 * vprintf (MSVCRT.@)
2479 int MSVCRT_vprintf(const char *format, va_list valist)
2481 return MSVCRT_vfprintf(MSVCRT_stdout,format,valist);
2484 /*********************************************************************
2485 * vwprintf (MSVCRT.@)
2487 int MSVCRT_vwprintf(const WCHAR *format, va_list valist)
2489 return MSVCRT_vfwprintf(MSVCRT_stdout,format,valist);
2492 /*********************************************************************
2493 * fprintf (MSVCRT.@)
2495 int MSVCRT_fprintf(MSVCRT_FILE* file, const char *format, ...)
2499 va_start(valist, format);
2500 res = MSVCRT_vfprintf(file, format, valist);
2505 /*********************************************************************
2506 * fwprintf (MSVCRT.@)
2508 int MSVCRT_fwprintf(MSVCRT_FILE* file, const WCHAR *format, ...)
2512 va_start(valist, format);
2513 res = MSVCRT_vfwprintf(file, format, valist);
2518 /*********************************************************************
2521 int MSVCRT_printf(const char *format, ...)
2525 va_start(valist, format);
2526 res = MSVCRT_vfprintf(MSVCRT_stdout, format, valist);
2531 /*********************************************************************
2534 int MSVCRT_ungetc(int c, MSVCRT_FILE * file)
2536 if(file->_bufsiz == 0 && !(file->_flag & MSVCRT__IONBF)) {
2537 msvcrt_alloc_buffer(file);
2540 if(file->_ptr>file->_base) {
2549 /*********************************************************************
2550 * ungetwc (MSVCRT.@)
2552 MSVCRT_wint_t MSVCRT_ungetwc(MSVCRT_wint_t wc, MSVCRT_FILE * file)
2555 char * pp = (char *)&mwc;
2557 for(i=sizeof(WCHAR)-1;i>=0;i--) {
2558 if(pp[i] != MSVCRT_ungetc(pp[i],file))
2564 /*********************************************************************
2565 * wprintf (MSVCRT.@)
2567 int MSVCRT_wprintf(const WCHAR *format, ...)
2571 va_start(valist, format);
2572 res = MSVCRT_vwprintf(format, valist);