include/mscvpdb.h: Use flexible array members for the rest of structures.
[wine.git] / dlls / msvcrt / file.c
blob05630fb54b102fe174b636e7f5cd53802589cced
1 /*
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
8 * Copyright 2004 Eric Pouech
9 * Copyright 2004 Juan Lang
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 #include <direct.h>
28 #include <fcntl.h>
29 #include <io.h>
30 #include <share.h>
31 #include <stdarg.h>
32 #include <sys/locking.h>
33 #include <sys/types.h>
34 #include <sys/utime.h>
35 #include <time.h>
36 #include <limits.h>
38 #include "windef.h"
39 #include "winbase.h"
40 #include "wincon.h"
41 #include "winternl.h"
42 #include "winnls.h"
43 #include "msvcrt.h"
44 #include "mtdll.h"
45 #include "wine/asm.h"
46 #include "wine/debug.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(msvcrt);
50 #undef _fstat
51 #undef _fstati64
52 #undef _stat
53 #undef _stati64
54 #undef _wstat
55 #undef _wstati64
56 #undef _fstat32
57 #undef _fstat32i64
58 #undef _stat32i64
59 #undef _stat32
60 #undef _wstat32
61 #undef _wstat32i64
62 #undef _fstat64i32
63 #undef _fstat64
64 #undef _stat64
65 #undef _stat64i32
66 #undef _wstat64i32
67 #undef _wstat64
69 /* for stat mode, permissions apply to all,owner and group */
70 #define ALL_S_IREAD (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6))
71 #define ALL_S_IWRITE (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6))
72 #define ALL_S_IEXEC (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6))
74 /* _access() bit flags FIXME: incomplete */
75 #define MSVCRT_W_OK 0x02
76 #define MSVCRT_R_OK 0x04
78 /* values for wxflag in file descriptor */
79 #define WX_OPEN 0x01
80 #define WX_ATEOF 0x02
81 #define WX_READNL 0x04 /* read started with \n */
82 #define WX_PIPE 0x08
83 #define WX_DONTINHERIT 0x10
84 #define WX_APPEND 0x20
85 #define WX_TTY 0x40
86 #define WX_TEXT 0x80
88 static char utf8_bom[3] = { 0xef, 0xbb, 0xbf };
89 static char utf16_bom[2] = { 0xff, 0xfe };
91 #define MSVCRT_INTERNAL_BUFSIZ 4096
93 enum textmode
95 TEXTMODE_ANSI,
96 TEXTMODE_UTF8,
97 TEXTMODE_UTF16LE,
100 #if _MSVCR_VER >= 140
102 #define MSVCRT_MAX_FILES 8192
103 #define MSVCRT_FD_BLOCK_SIZE 64
105 typedef struct {
106 CRITICAL_SECTION crit;
107 HANDLE handle;
108 __int64 startpos;
109 unsigned char wxflag;
110 char textmode;
111 char lookahead[3];
112 unsigned int unicode : 1;
113 unsigned int utf8translations : 1;
114 unsigned int dbcsBufferUsed : 1;
115 char dbcsBuffer[MB_LEN_MAX];
116 } ioinfo;
118 /*********************************************************************
119 * __badioinfo (MSVCRT.@)
121 ioinfo MSVCRT___badioinfo = { {0}, INVALID_HANDLE_VALUE, 0, WX_TEXT };
122 #else
124 #define MSVCRT_MAX_FILES 2048
125 #define MSVCRT_FD_BLOCK_SIZE 32
127 typedef struct {
128 HANDLE handle;
129 unsigned char wxflag;
130 char lookahead[3];
131 int exflag;
132 CRITICAL_SECTION crit;
133 #if _MSVCR_VER >= 80
134 char textmode : 7;
135 char unicode : 1;
136 char pipech2[2];
137 __int64 startpos;
138 BOOL utf8translations;
139 char dbcsBuffer[1];
140 BOOL dbcsBufferUsed;
141 #endif
142 } ioinfo;
144 /*********************************************************************
145 * __badioinfo (MSVCRT.@)
147 ioinfo MSVCRT___badioinfo = { INVALID_HANDLE_VALUE, WX_TEXT };
148 #endif
150 /*********************************************************************
151 * __pioinfo (MSVCRT.@)
152 * array of pointers to ioinfo arrays [32]
154 ioinfo * MSVCRT___pioinfo[MSVCRT_MAX_FILES/MSVCRT_FD_BLOCK_SIZE] = { 0 };
156 #if _MSVCR_VER >= 80
158 #if _MSVCR_VER >= 140
159 static inline BOOL ioinfo_is_crit_init(ioinfo *info)
161 return TRUE;
164 static inline void ioinfo_set_crit_init(ioinfo *info)
167 #else
168 static inline BOOL ioinfo_is_crit_init(ioinfo *info)
170 return info->exflag & 1;
173 static inline void ioinfo_set_crit_init(ioinfo *info)
175 info->exflag |= 1;
177 #endif
179 static inline enum textmode ioinfo_get_textmode(ioinfo *info)
181 return info->textmode;
184 static inline void ioinfo_set_textmode(ioinfo *info, enum textmode mode)
186 info->textmode = mode;
189 static inline void ioinfo_set_unicode(ioinfo *info, BOOL unicode)
191 info->unicode = !!unicode;
193 #else
195 #define EF_UTF8 0x01
196 #define EF_UTF16 0x02
197 #define EF_CRIT_INIT 0x04
198 #define EF_UNK_UNICODE 0x08
200 static inline BOOL ioinfo_is_crit_init(ioinfo *info)
202 return info->exflag & EF_CRIT_INIT;
205 static inline void ioinfo_set_crit_init(ioinfo *info)
207 info->exflag |= EF_CRIT_INIT;
210 static inline enum textmode ioinfo_get_textmode(ioinfo *info)
212 if (info->exflag & EF_UTF8)
213 return TEXTMODE_UTF8;
214 if (info->exflag & EF_UTF16)
215 return TEXTMODE_UTF16LE;
216 return TEXTMODE_ANSI;
219 static inline void ioinfo_set_textmode(ioinfo *info, enum textmode mode)
221 info->exflag &= EF_CRIT_INIT | EF_UNK_UNICODE;
222 switch (mode)
224 case TEXTMODE_ANSI:
225 break;
226 case TEXTMODE_UTF8:
227 info->exflag |= EF_UTF8;
228 break;
229 case TEXTMODE_UTF16LE:
230 info->exflag |= EF_UTF16;
231 break;
235 static inline void ioinfo_set_unicode(ioinfo *info, BOOL unicode)
237 if (unicode)
238 info->exflag |= EF_UNK_UNICODE;
239 else
240 info->exflag &= ~EF_UNK_UNICODE;
242 #endif
244 typedef struct {
245 FILE file;
246 CRITICAL_SECTION crit;
247 } file_crit;
249 #if _MSVCR_VER >= 140
250 file_crit MSVCRT__iob[_IOB_ENTRIES] = { 0 };
252 static FILE* iob_get_file(int i)
254 return &MSVCRT__iob[i].file;
257 static CRITICAL_SECTION* file_get_cs(FILE *f)
259 return &((file_crit*)f)->crit;
261 #else
262 FILE MSVCRT__iob[_IOB_ENTRIES] = { { 0 } };
264 static FILE* iob_get_file(int i)
266 return &MSVCRT__iob[i];
269 static CRITICAL_SECTION* file_get_cs(FILE *f)
271 if (f < iob_get_file(0) || f >= iob_get_file(_IOB_ENTRIES))
272 return &((file_crit*)f)->crit;
273 return NULL;
275 #endif
277 static file_crit* MSVCRT_fstream[MSVCRT_MAX_FILES/MSVCRT_FD_BLOCK_SIZE];
278 static int MSVCRT_max_streams = 512, MSVCRT_stream_idx;
280 /* INTERNAL: process umask */
281 static int MSVCRT_umask = 0;
283 /* INTERNAL: static data for tmpnam and _wtmpname functions */
284 static LONG tmpnam_unique;
285 static LONG tmpnam_s_unique;
287 static const unsigned int EXE = 'e' << 16 | 'x' << 8 | 'e';
288 static const unsigned int BAT = 'b' << 16 | 'a' << 8 | 't';
289 static const unsigned int CMD = 'c' << 16 | 'm' << 8 | 'd';
290 static const unsigned int COM = 'c' << 16 | 'o' << 8 | 'm';
292 #define TOUL(x) (ULONGLONG)(x)
293 static const ULONGLONG WCEXE = TOUL('e') << 32 | TOUL('x') << 16 | TOUL('e');
294 static const ULONGLONG WCBAT = TOUL('b') << 32 | TOUL('a') << 16 | TOUL('t');
295 static const ULONGLONG WCCMD = TOUL('c') << 32 | TOUL('m') << 16 | TOUL('d');
296 static const ULONGLONG WCCOM = TOUL('c') << 32 | TOUL('o') << 16 | TOUL('m');
298 /* This critical section protects the MSVCRT_fstreams table
299 * and MSVCRT_stream_idx from race conditions. It also
300 * protects fd critical sections creation code.
302 static CRITICAL_SECTION MSVCRT_file_cs;
303 static CRITICAL_SECTION_DEBUG MSVCRT_file_cs_debug =
305 0, 0, &MSVCRT_file_cs,
306 { &MSVCRT_file_cs_debug.ProcessLocksList, &MSVCRT_file_cs_debug.ProcessLocksList },
307 0, 0, { (DWORD_PTR)(__FILE__ ": MSVCRT_file_cs") }
309 static CRITICAL_SECTION MSVCRT_file_cs = { &MSVCRT_file_cs_debug, -1, 0, 0, 0, 0 };
310 #define LOCK_FILES() do { EnterCriticalSection(&MSVCRT_file_cs); } while (0)
311 #define UNLOCK_FILES() do { LeaveCriticalSection(&MSVCRT_file_cs); } while (0)
313 static void msvcrt_stat64_to_stat(const struct _stat64 *buf64, struct _stat *buf)
315 buf->st_dev = buf64->st_dev;
316 buf->st_ino = buf64->st_ino;
317 buf->st_mode = buf64->st_mode;
318 buf->st_nlink = buf64->st_nlink;
319 buf->st_uid = buf64->st_uid;
320 buf->st_gid = buf64->st_gid;
321 buf->st_rdev = buf64->st_rdev;
322 buf->st_size = buf64->st_size;
323 buf->st_atime = buf64->st_atime;
324 buf->st_mtime = buf64->st_mtime;
325 buf->st_ctime = buf64->st_ctime;
328 static void msvcrt_stat64_to_stati64(const struct _stat64 *buf64, struct _stati64 *buf)
330 buf->st_dev = buf64->st_dev;
331 buf->st_ino = buf64->st_ino;
332 buf->st_mode = buf64->st_mode;
333 buf->st_nlink = buf64->st_nlink;
334 buf->st_uid = buf64->st_uid;
335 buf->st_gid = buf64->st_gid;
336 buf->st_rdev = buf64->st_rdev;
337 buf->st_size = buf64->st_size;
338 buf->st_atime = buf64->st_atime;
339 buf->st_mtime = buf64->st_mtime;
340 buf->st_ctime = buf64->st_ctime;
343 static void msvcrt_stat64_to_stat32(const struct _stat64 *buf64, struct _stat32 *buf)
345 buf->st_dev = buf64->st_dev;
346 buf->st_ino = buf64->st_ino;
347 buf->st_mode = buf64->st_mode;
348 buf->st_nlink = buf64->st_nlink;
349 buf->st_uid = buf64->st_uid;
350 buf->st_gid = buf64->st_gid;
351 buf->st_rdev = buf64->st_rdev;
352 buf->st_size = buf64->st_size;
353 buf->st_atime = buf64->st_atime;
354 buf->st_mtime = buf64->st_mtime;
355 buf->st_ctime = buf64->st_ctime;
358 static void msvcrt_stat64_to_stat64i32(const struct _stat64 *buf64, struct _stat64i32 *buf)
360 buf->st_dev = buf64->st_dev;
361 buf->st_ino = buf64->st_ino;
362 buf->st_mode = buf64->st_mode;
363 buf->st_nlink = buf64->st_nlink;
364 buf->st_uid = buf64->st_uid;
365 buf->st_gid = buf64->st_gid;
366 buf->st_rdev = buf64->st_rdev;
367 buf->st_size = buf64->st_size;
368 buf->st_atime = buf64->st_atime;
369 buf->st_mtime = buf64->st_mtime;
370 buf->st_ctime = buf64->st_ctime;
373 static void msvcrt_stat64_to_stat32i64(const struct _stat64 *buf64, struct _stat32i64 *buf)
375 buf->st_dev = buf64->st_dev;
376 buf->st_ino = buf64->st_ino;
377 buf->st_mode = buf64->st_mode;
378 buf->st_nlink = buf64->st_nlink;
379 buf->st_uid = buf64->st_uid;
380 buf->st_gid = buf64->st_gid;
381 buf->st_rdev = buf64->st_rdev;
382 buf->st_size = buf64->st_size;
383 buf->st_atime = buf64->st_atime;
384 buf->st_mtime = buf64->st_mtime;
385 buf->st_ctime = buf64->st_ctime;
388 static void time_to_filetime( __time64_t time, FILETIME *ft )
390 /* 1601 to 1970 is 369 years plus 89 leap days */
391 static const __int64 secs_1601_to_1970 = ((369 * 365 + 89) * (__int64)86400);
393 __int64 ticks = (time + secs_1601_to_1970) * 10000000;
394 ft->dwHighDateTime = ticks >> 32;
395 ft->dwLowDateTime = ticks;
398 static inline ioinfo* get_ioinfo_nolock(int fd)
400 ioinfo *ret = NULL;
401 if(fd>=0 && fd<MSVCRT_MAX_FILES)
402 ret = MSVCRT___pioinfo[fd/MSVCRT_FD_BLOCK_SIZE];
403 if(!ret)
404 return &MSVCRT___badioinfo;
406 return ret + (fd%MSVCRT_FD_BLOCK_SIZE);
409 static inline void init_ioinfo_cs(ioinfo *info)
411 if(!ioinfo_is_crit_init(info)) {
412 LOCK_FILES();
413 if(!ioinfo_is_crit_init(info)) {
414 InitializeCriticalSection(&info->crit);
415 ioinfo_set_crit_init(info);
417 UNLOCK_FILES();
421 static inline ioinfo* get_ioinfo(int fd)
423 ioinfo *ret = get_ioinfo_nolock(fd);
424 if(ret == &MSVCRT___badioinfo)
425 return ret;
426 init_ioinfo_cs(ret);
427 EnterCriticalSection(&ret->crit);
428 return ret;
431 static inline BOOL alloc_pioinfo_block(int fd)
433 ioinfo *block;
434 int i;
436 if(fd<0 || fd>=MSVCRT_MAX_FILES)
438 *_errno() = ENFILE;
439 return FALSE;
442 block = calloc(MSVCRT_FD_BLOCK_SIZE, sizeof(ioinfo));
443 if(!block)
445 WARN(":out of memory!\n");
446 *_errno() = ENOMEM;
447 return FALSE;
449 for(i=0; i<MSVCRT_FD_BLOCK_SIZE; i++)
451 block[i].handle = INVALID_HANDLE_VALUE;
452 if (ioinfo_is_crit_init(&block[i]))
454 /* Initialize crit section on block allocation for _MSVC_VER >= 140,
455 * ioinfo_is_crit_init() is always TRUE. */
456 InitializeCriticalSection(&block[i].crit);
459 if(InterlockedCompareExchangePointer((void**)&MSVCRT___pioinfo[fd/MSVCRT_FD_BLOCK_SIZE], block, NULL))
461 if (ioinfo_is_crit_init(&block[0]))
463 for(i = 0; i < MSVCRT_FD_BLOCK_SIZE; ++i)
464 DeleteCriticalSection(&block[i].crit);
466 free(block);
468 return TRUE;
471 static inline ioinfo* get_ioinfo_alloc_fd(int fd)
473 ioinfo *ret;
475 ret = get_ioinfo(fd);
476 if(ret != &MSVCRT___badioinfo)
477 return ret;
479 if(!alloc_pioinfo_block(fd))
480 return &MSVCRT___badioinfo;
482 return get_ioinfo(fd);
485 static inline ioinfo* get_ioinfo_alloc(int *fd)
487 int i;
489 *fd = -1;
490 for(i=0; i<MSVCRT_MAX_FILES; i++)
492 ioinfo *info = get_ioinfo_nolock(i);
494 if(info == &MSVCRT___badioinfo)
496 if(!alloc_pioinfo_block(i))
497 return &MSVCRT___badioinfo;
498 info = get_ioinfo_nolock(i);
501 init_ioinfo_cs(info);
502 if(TryEnterCriticalSection(&info->crit))
504 if(info->handle == INVALID_HANDLE_VALUE)
506 *fd = i;
507 return info;
509 LeaveCriticalSection(&info->crit);
513 WARN(":files exhausted!\n");
514 *_errno() = ENFILE;
515 return &MSVCRT___badioinfo;
518 static inline void release_ioinfo(ioinfo *info)
520 if(info!=&MSVCRT___badioinfo && ioinfo_is_crit_init(info))
521 LeaveCriticalSection(&info->crit);
524 static inline FILE* msvcrt_get_file(int i)
526 file_crit *ret;
528 if(i >= MSVCRT_max_streams)
529 return NULL;
531 if(i < _IOB_ENTRIES)
532 return iob_get_file(i);
534 ret = MSVCRT_fstream[i/MSVCRT_FD_BLOCK_SIZE];
535 if(!ret) {
536 MSVCRT_fstream[i/MSVCRT_FD_BLOCK_SIZE] = calloc(MSVCRT_FD_BLOCK_SIZE, sizeof(file_crit));
537 if(!MSVCRT_fstream[i/MSVCRT_FD_BLOCK_SIZE]) {
538 ERR("out of memory\n");
539 *_errno() = ENOMEM;
540 return NULL;
543 ret = MSVCRT_fstream[i/MSVCRT_FD_BLOCK_SIZE] + (i%MSVCRT_FD_BLOCK_SIZE);
544 } else
545 ret += i%MSVCRT_FD_BLOCK_SIZE;
547 return &ret->file;
550 /* INTERNAL: free a file entry fd */
551 static void msvcrt_free_fd(int fd)
553 ioinfo *fdinfo = get_ioinfo(fd);
555 if(fdinfo != &MSVCRT___badioinfo)
557 fdinfo->handle = INVALID_HANDLE_VALUE;
558 fdinfo->wxflag = 0;
560 TRACE(":fd (%d) freed\n",fd);
562 if (fd < 3)
564 switch (fd)
566 case 0:
567 SetStdHandle(STD_INPUT_HANDLE, 0);
568 break;
569 case 1:
570 SetStdHandle(STD_OUTPUT_HANDLE, 0);
571 break;
572 case 2:
573 SetStdHandle(STD_ERROR_HANDLE, 0);
574 break;
577 release_ioinfo(fdinfo);
580 static void msvcrt_set_fd(ioinfo *fdinfo, HANDLE hand, int flag)
582 fdinfo->handle = hand;
583 fdinfo->wxflag = WX_OPEN | (flag & (WX_DONTINHERIT | WX_APPEND | WX_TEXT | WX_PIPE | WX_TTY));
584 fdinfo->lookahead[0] = '\n';
585 fdinfo->lookahead[1] = '\n';
586 fdinfo->lookahead[2] = '\n';
587 ioinfo_set_unicode(fdinfo, FALSE);
588 ioinfo_set_textmode(fdinfo, TEXTMODE_ANSI);
590 if (hand != MSVCRT_NO_CONSOLE)
592 switch (fdinfo-MSVCRT___pioinfo[0])
594 case 0: SetStdHandle(STD_INPUT_HANDLE, hand); break;
595 case 1: SetStdHandle(STD_OUTPUT_HANDLE, hand); break;
596 case 2: SetStdHandle(STD_ERROR_HANDLE, hand); break;
601 /* INTERNAL: Allocate an fd slot from a Win32 HANDLE */
602 static int msvcrt_alloc_fd(HANDLE hand, int flag)
604 int fd;
605 ioinfo *info = get_ioinfo_alloc(&fd);
607 TRACE(":handle (%p) allocating fd (%d)\n", hand, fd);
609 if(info == &MSVCRT___badioinfo)
610 return -1;
612 msvcrt_set_fd(info, hand, flag);
613 release_ioinfo(info);
614 return fd;
617 /* INTERNAL: Allocate a FILE* for an fd slot */
618 /* caller must hold the files lock */
619 static FILE* msvcrt_alloc_fp(void)
621 int i;
622 FILE *file;
624 for (i = 3; i < MSVCRT_max_streams; i++)
626 file = msvcrt_get_file(i);
627 if (!file)
628 return NULL;
630 if (file->_flag == 0)
632 if (i == MSVCRT_stream_idx)
634 CRITICAL_SECTION *cs = file_get_cs(file);
635 if (cs)
637 InitializeCriticalSectionEx(cs, 0, RTL_CRITICAL_SECTION_FLAG_FORCE_DEBUG_INFO);
638 cs->DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": file_crit.crit");
640 MSVCRT_stream_idx++;
642 return file;
646 return NULL;
649 /* INTERNAL: initialize a FILE* from an open fd */
650 static int msvcrt_init_fp(FILE* file, int fd, unsigned stream_flags)
652 TRACE(":fd (%d) allocating FILE*\n",fd);
653 if (!(get_ioinfo_nolock(fd)->wxflag & WX_OPEN))
655 WARN(":invalid fd %d\n",fd);
656 *__doserrno() = 0;
657 *_errno() = EBADF;
658 return -1;
660 file->_ptr = file->_base = NULL;
661 file->_cnt = 0;
662 file->_file = fd;
663 file->_flag = stream_flags;
664 file->_tmpfname = NULL;
666 TRACE(":got FILE* (%p)\n",file);
667 return 0;
670 /* INTERNAL: Create an inheritance data block (for spawned process)
671 * The inheritance block is made of:
672 * 00 int nb of file descriptor (NBFD)
673 * 04 char file flags (wxflag): repeated for each fd
674 * 4+NBFD HANDLE file handle: repeated for each fd
676 BOOL msvcrt_create_io_inherit_block(WORD *size, BYTE **block)
678 int fd, last_fd;
679 char* wxflag_ptr;
680 HANDLE* handle_ptr;
681 ioinfo* fdinfo;
683 for (last_fd=MSVCRT_MAX_FILES-1; last_fd>=0; last_fd--)
684 if (get_ioinfo_nolock(last_fd)->handle != INVALID_HANDLE_VALUE)
685 break;
686 last_fd++;
688 *size = sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * last_fd;
689 *block = calloc(1, *size);
690 if (!*block)
692 *size = 0;
693 return FALSE;
695 wxflag_ptr = (char*)*block + sizeof(unsigned);
696 handle_ptr = (HANDLE*)(wxflag_ptr + last_fd);
698 *(unsigned*)*block = last_fd;
699 for (fd = 0; fd < last_fd; fd++)
701 /* to be inherited, we need it to be open, and that DONTINHERIT isn't set */
702 fdinfo = get_ioinfo_nolock(fd);
703 if ((fdinfo->wxflag & (WX_OPEN | WX_DONTINHERIT)) == WX_OPEN)
705 *wxflag_ptr = fdinfo->wxflag;
706 *handle_ptr = fdinfo->handle;
708 else
710 *wxflag_ptr = 0;
711 *handle_ptr = INVALID_HANDLE_VALUE;
713 wxflag_ptr++; handle_ptr++;
715 return TRUE;
718 /* INTERNAL: Set up all file descriptors,
719 * as well as default streams (stdin, stderr and stdout)
721 void msvcrt_init_io(void)
723 STARTUPINFOA si;
724 int i;
725 ioinfo *fdinfo;
727 GetStartupInfoA(&si);
728 if (si.cbReserved2 >= sizeof(unsigned int) && si.lpReserved2 != NULL)
730 BYTE* wxflag_ptr;
731 HANDLE* handle_ptr;
732 unsigned int count;
734 count = *(unsigned*)si.lpReserved2;
735 wxflag_ptr = si.lpReserved2 + sizeof(unsigned);
736 handle_ptr = (HANDLE*)(wxflag_ptr + count);
738 count = min(count, (si.cbReserved2 - sizeof(unsigned)) / (sizeof(HANDLE) + 1));
739 count = min(count, MSVCRT_MAX_FILES);
740 for (i = 0; i < count; i++)
742 if ((*wxflag_ptr & WX_OPEN) && GetFileType(*handle_ptr) != FILE_TYPE_UNKNOWN)
744 fdinfo = get_ioinfo_alloc_fd(i);
745 if(fdinfo != &MSVCRT___badioinfo)
746 msvcrt_set_fd(fdinfo, *handle_ptr, *wxflag_ptr);
747 release_ioinfo(fdinfo);
750 wxflag_ptr++; handle_ptr++;
754 fdinfo = get_ioinfo_alloc_fd(STDIN_FILENO);
755 if (!(fdinfo->wxflag & WX_OPEN) || fdinfo->handle == INVALID_HANDLE_VALUE) {
756 HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
757 DWORD flags = WX_OPEN | WX_TEXT;
758 DWORD type = GetFileType(h);
760 if (type == FILE_TYPE_UNKNOWN) {
761 h = MSVCRT_NO_CONSOLE;
762 flags |= WX_TTY;
763 } else if ((type & 0xf) == FILE_TYPE_CHAR) {
764 flags |= WX_TTY;
765 } else if ((type & 0xf) == FILE_TYPE_PIPE) {
766 flags |= WX_PIPE;
769 msvcrt_set_fd(fdinfo, h, flags);
771 release_ioinfo(fdinfo);
773 fdinfo = get_ioinfo_alloc_fd(STDOUT_FILENO);
774 if (!(fdinfo->wxflag & WX_OPEN) || fdinfo->handle == INVALID_HANDLE_VALUE) {
775 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
776 DWORD flags = WX_OPEN | WX_TEXT;
777 DWORD type = GetFileType(h);
779 if (type == FILE_TYPE_UNKNOWN) {
780 h = MSVCRT_NO_CONSOLE;
781 flags |= WX_TTY;
782 } else if ((type & 0xf) == FILE_TYPE_CHAR) {
783 flags |= WX_TTY;
784 } else if ((type & 0xf) == FILE_TYPE_PIPE) {
785 flags |= WX_PIPE;
788 msvcrt_set_fd(fdinfo, h, flags);
790 release_ioinfo(fdinfo);
792 fdinfo = get_ioinfo_alloc_fd(STDERR_FILENO);
793 if (!(fdinfo->wxflag & WX_OPEN) || fdinfo->handle == INVALID_HANDLE_VALUE) {
794 HANDLE h = GetStdHandle(STD_ERROR_HANDLE);
795 DWORD flags = WX_OPEN | WX_TEXT;
796 DWORD type = GetFileType(h);
798 if (type == FILE_TYPE_UNKNOWN) {
799 h = MSVCRT_NO_CONSOLE;
800 flags |= WX_TTY;
801 } else if ((type & 0xf) == FILE_TYPE_CHAR) {
802 flags |= WX_TTY;
803 } else if ((type & 0xf) == FILE_TYPE_PIPE) {
804 flags |= WX_PIPE;
807 msvcrt_set_fd(fdinfo, h, flags);
809 release_ioinfo(fdinfo);
811 TRACE(":handles (%p)(%p)(%p)\n", get_ioinfo_nolock(STDIN_FILENO)->handle,
812 get_ioinfo_nolock(STDOUT_FILENO)->handle,
813 get_ioinfo_nolock(STDERR_FILENO)->handle);
815 for (i = 0; i < 3; i++)
817 FILE *f = iob_get_file(i);
818 CRITICAL_SECTION *cs = file_get_cs(f);
820 /* FILE structs for stdin/out/err are static and never deleted */
821 f->_file = get_ioinfo_nolock(i)->handle == MSVCRT_NO_CONSOLE ?
822 MSVCRT_NO_CONSOLE_FD : i;
823 f->_tmpfname = NULL;
824 f->_flag = (i == 0) ? _IOREAD : _IOWRT;
826 if (cs)
828 InitializeCriticalSectionEx(cs, 0, RTL_CRITICAL_SECTION_FLAG_FORCE_DEBUG_INFO);
829 cs->DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": file_crit.crit");
832 MSVCRT_stream_idx = 3;
835 /* INTERNAL: Flush stdio file buffer */
836 static int msvcrt_flush_buffer(FILE* file)
838 int ret = 0;
840 if((file->_flag & (_IOREAD|_IOWRT)) == _IOWRT &&
841 file->_flag & (_IOMYBUF|MSVCRT__USERBUF)) {
842 int cnt=file->_ptr-file->_base;
843 if(cnt>0 && _write(file->_file, file->_base, cnt) != cnt) {
844 file->_flag |= _IOERR;
845 ret = EOF;
846 } else if(file->_flag & _IORW) {
847 file->_flag &= ~_IOWRT;
851 file->_ptr=file->_base;
852 file->_cnt=0;
853 return ret;
856 /*********************************************************************
857 * _isatty (MSVCRT.@)
859 int CDECL _isatty(int fd)
861 TRACE(":fd (%d)\n",fd);
863 return get_ioinfo_nolock(fd)->wxflag & WX_TTY;
866 /* INTERNAL: Allocate stdio file buffer */
867 static BOOL msvcrt_alloc_buffer(FILE* file)
869 #if _MSVCR_VER >= 140
870 if((file->_file==STDOUT_FILENO && _isatty(file->_file))
871 || file->_file == STDERR_FILENO)
872 return FALSE;
873 #else
874 if((file->_file==STDOUT_FILENO || file->_file==STDERR_FILENO)
875 && _isatty(file->_file))
876 return FALSE;
877 #endif
879 file->_base = calloc(1, MSVCRT_INTERNAL_BUFSIZ);
880 if(file->_base) {
881 file->_bufsiz = MSVCRT_INTERNAL_BUFSIZ;
882 file->_flag |= _IOMYBUF;
883 } else {
884 file->_base = (char*)(&file->_charbuf);
885 file->_bufsiz = 2;
886 file->_flag |= MSVCRT__NOBUF;
888 file->_ptr = file->_base;
889 file->_cnt = 0;
890 return TRUE;
893 /* INTERNAL: Allocate temporary buffer for stdout and stderr */
894 static BOOL add_std_buffer(FILE *file)
896 static char buffers[2][BUFSIZ];
898 if((file->_file!=STDOUT_FILENO && file->_file!=STDERR_FILENO)
899 || (file->_flag & (MSVCRT__NOBUF | _IOMYBUF | MSVCRT__USERBUF))
900 || !_isatty(file->_file))
901 return FALSE;
903 file->_ptr = file->_base = buffers[file->_file == STDOUT_FILENO ? 0 : 1];
904 file->_bufsiz = file->_cnt = BUFSIZ;
905 file->_flag |= MSVCRT__USERBUF;
906 return TRUE;
909 /* INTERNAL: Removes temporary buffer from stdout or stderr */
910 /* Only call this function when add_std_buffer returned TRUE */
911 static void remove_std_buffer(FILE *file)
913 msvcrt_flush_buffer(file);
914 file->_ptr = file->_base = NULL;
915 file->_bufsiz = file->_cnt = 0;
916 file->_flag &= ~MSVCRT__USERBUF;
919 /* INTERNAL: Convert integer to base32 string (0-9a-v), 0 becomes "" */
920 static int msvcrt_int_to_base32(int num, char *str)
922 char *p;
923 int n = num;
924 int digits = 0;
926 while (n != 0)
928 n >>= 5;
929 digits++;
931 p = str + digits;
932 *p = 0;
933 while (--p >= str)
935 *p = (num & 31) + '0';
936 if (*p > '9')
937 *p += ('a' - '0' - 10);
938 num >>= 5;
941 return digits;
944 /* INTERNAL: wide character version of msvcrt_int_to_base32 */
945 static int msvcrt_int_to_base32_w(int num, wchar_t *str)
947 wchar_t *p;
948 int n = num;
949 int digits = 0;
951 while (n != 0)
953 n >>= 5;
954 digits++;
956 p = str + digits;
957 *p = 0;
958 while (--p >= str)
960 *p = (num & 31) + '0';
961 if (*p > '9')
962 *p += ('a' - '0' - 10);
963 num >>= 5;
966 return digits;
969 /*********************************************************************
970 * __iob_func (MSVCRT.@)
972 #undef __iob_func
973 FILE * CDECL __iob_func(void)
975 return iob_get_file(0);
978 #if _MSVCR_VER >= 140
979 /*********************************************************************
980 * __acrt_iob_func(UCRTBASE.@)
982 FILE * CDECL __acrt_iob_func(unsigned idx)
984 return iob_get_file(idx);
986 #endif
988 /*********************************************************************
989 * _access (MSVCRT.@)
991 int CDECL _access(const char *filename, int mode)
993 DWORD attr = GetFileAttributesA(filename);
995 TRACE("(%s,%d) %ld\n", filename, mode, attr);
997 if (!filename || attr == INVALID_FILE_ATTRIBUTES)
999 msvcrt_set_errno(GetLastError());
1000 return -1;
1002 if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
1004 msvcrt_set_errno(ERROR_ACCESS_DENIED);
1005 return -1;
1007 return 0;
1010 /*********************************************************************
1011 * _access_s (MSVCRT.@)
1013 int CDECL _access_s(const char *filename, int mode)
1015 if (!MSVCRT_CHECK_PMT(filename != NULL)) return *_errno();
1016 if (!MSVCRT_CHECK_PMT((mode & ~(MSVCRT_R_OK | MSVCRT_W_OK)) == 0)) return *_errno();
1018 if (_access(filename, mode) == -1)
1019 return *_errno();
1020 return 0;
1023 /*********************************************************************
1024 * _waccess (MSVCRT.@)
1026 int CDECL _waccess(const wchar_t *filename, int mode)
1028 DWORD attr = GetFileAttributesW(filename);
1030 TRACE("(%s,%d) %ld\n", debugstr_w(filename), mode, attr);
1032 if (!filename || attr == INVALID_FILE_ATTRIBUTES)
1034 msvcrt_set_errno(GetLastError());
1035 return -1;
1037 if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & MSVCRT_W_OK))
1039 msvcrt_set_errno(ERROR_ACCESS_DENIED);
1040 return -1;
1042 return 0;
1045 /*********************************************************************
1046 * _waccess_s (MSVCRT.@)
1048 int CDECL _waccess_s(const wchar_t *filename, int mode)
1050 if (!MSVCRT_CHECK_PMT(filename != NULL)) return *_errno();
1051 if (!MSVCRT_CHECK_PMT((mode & ~(MSVCRT_R_OK | MSVCRT_W_OK)) == 0)) return *_errno();
1053 if (_waccess(filename, mode) == -1)
1054 return *_errno();
1055 return 0;
1058 /*********************************************************************
1059 * _chmod (MSVCRT.@)
1061 int CDECL _chmod(const char *path, int flags)
1063 DWORD oldFlags = GetFileAttributesA(path);
1065 if (oldFlags != INVALID_FILE_ATTRIBUTES)
1067 DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
1068 oldFlags | FILE_ATTRIBUTE_READONLY;
1070 if (newFlags == oldFlags || SetFileAttributesA(path, newFlags))
1071 return 0;
1073 msvcrt_set_errno(GetLastError());
1074 return -1;
1077 /*********************************************************************
1078 * _wchmod (MSVCRT.@)
1080 int CDECL _wchmod(const wchar_t *path, int flags)
1082 DWORD oldFlags = GetFileAttributesW(path);
1084 if (oldFlags != INVALID_FILE_ATTRIBUTES)
1086 DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
1087 oldFlags | FILE_ATTRIBUTE_READONLY;
1089 if (newFlags == oldFlags || SetFileAttributesW(path, newFlags))
1090 return 0;
1092 msvcrt_set_errno(GetLastError());
1093 return -1;
1096 /*********************************************************************
1097 * _unlink (MSVCRT.@)
1099 int CDECL _unlink(const char *path)
1101 TRACE("%s\n", debugstr_a(path));
1102 if(DeleteFileA(path))
1103 return 0;
1104 TRACE("failed (%ld)\n", GetLastError());
1105 msvcrt_set_errno(GetLastError());
1106 return -1;
1109 /*********************************************************************
1110 * _wunlink (MSVCRT.@)
1112 int CDECL _wunlink(const wchar_t *path)
1114 TRACE("(%s)\n", debugstr_w(path));
1115 if(DeleteFileW(path))
1116 return 0;
1117 TRACE("failed (%ld)\n", GetLastError());
1118 msvcrt_set_errno(GetLastError());
1119 return -1;
1122 /*********************************************************************
1123 * _commit (MSVCRT.@)
1125 int CDECL _commit(int fd)
1127 ioinfo *info = get_ioinfo(fd);
1128 int ret;
1130 TRACE(":fd (%d) handle (%p)\n", fd, info->handle);
1132 if (info->handle == INVALID_HANDLE_VALUE)
1133 ret = -1;
1134 else if (!FlushFileBuffers(info->handle))
1136 if (GetLastError() == ERROR_INVALID_HANDLE)
1138 /* FlushFileBuffers fails for console handles
1139 * so we ignore this error.
1141 ret = 0;
1143 else
1145 TRACE(":failed-last error (%ld)\n", GetLastError());
1146 msvcrt_set_errno(GetLastError());
1147 ret = -1;
1150 else
1152 TRACE(":ok\n");
1153 ret = 0;
1156 release_ioinfo(info);
1157 return ret;
1160 /* INTERNAL: Flush all stream buffer */
1161 static int msvcrt_flush_all_buffers(int mask)
1163 int i, num_flushed = 0;
1164 FILE *file;
1166 LOCK_FILES();
1167 for (i = 0; i < MSVCRT_stream_idx; i++) {
1168 file = msvcrt_get_file(i);
1170 if (file->_flag)
1172 if(file->_flag & mask) {
1173 fflush(file);
1174 num_flushed++;
1178 UNLOCK_FILES();
1180 TRACE(":flushed (%d) handles\n",num_flushed);
1181 return num_flushed;
1184 /*********************************************************************
1185 * _flushall (MSVCRT.@)
1187 int CDECL _flushall(void)
1189 return msvcrt_flush_all_buffers(_IOWRT | _IOREAD);
1192 /*********************************************************************
1193 * fflush (MSVCRT.@)
1195 int CDECL fflush(FILE* file)
1197 int ret;
1199 if(!file) {
1200 msvcrt_flush_all_buffers(_IOWRT);
1201 ret = 0;
1202 } else {
1203 _lock_file(file);
1204 ret = _fflush_nolock(file);
1205 _unlock_file(file);
1208 return ret;
1211 /*********************************************************************
1212 * _fflush_nolock (MSVCRT.@)
1214 int CDECL _fflush_nolock(FILE* file)
1216 int res;
1218 if(!file) {
1219 msvcrt_flush_all_buffers(_IOWRT);
1220 return 0;
1223 res = msvcrt_flush_buffer(file);
1224 if(!res && (file->_flag & MSVCRT__IOCOMMIT))
1225 res = _commit(file->_file) ? EOF : 0;
1226 return res;
1229 /*********************************************************************
1230 * _close (MSVCRT.@)
1232 int CDECL _close(int fd)
1234 ioinfo *info = get_ioinfo(fd);
1235 int ret;
1237 TRACE(":fd (%d) handle (%p)\n", fd, info->handle);
1239 if (fd == MSVCRT_NO_CONSOLE_FD) {
1240 *_errno() = EBADF;
1241 ret = -1;
1242 } else if (!MSVCRT_CHECK_PMT_ERR(info->wxflag & WX_OPEN, EBADF)) {
1243 ret = -1;
1244 } else if (fd == STDOUT_FILENO &&
1245 info->handle == get_ioinfo_nolock(STDERR_FILENO)->handle) {
1246 msvcrt_free_fd(fd);
1247 ret = 0;
1248 } else if (fd == STDERR_FILENO &&
1249 info->handle == get_ioinfo_nolock(STDOUT_FILENO)->handle) {
1250 msvcrt_free_fd(fd);
1251 ret = 0;
1252 } else {
1253 ret = CloseHandle(info->handle) ? 0 : -1;
1254 msvcrt_free_fd(fd);
1255 if (ret) {
1256 WARN(":failed-last error (%ld)\n", GetLastError());
1257 msvcrt_set_errno(GetLastError());
1260 release_ioinfo(info);
1261 return ret;
1264 /*********************************************************************
1265 * _dup2 (MSVCRT.@)
1266 * NOTES
1267 * MSDN isn't clear on this point, but the remarks for _pipe
1268 * indicate file descriptors duplicated with _dup and _dup2 are always
1269 * inheritable.
1271 int CDECL _dup2(int od, int nd)
1273 ioinfo *info_od, *info_nd;
1274 int ret;
1276 TRACE("(od=%d, nd=%d)\n", od, nd);
1278 if (od < nd)
1280 info_od = get_ioinfo(od);
1281 info_nd = get_ioinfo_alloc_fd(nd);
1283 else
1285 info_nd = get_ioinfo_alloc_fd(nd);
1286 info_od = get_ioinfo(od);
1289 if (info_nd == &MSVCRT___badioinfo)
1291 *_errno() = EBADF;
1292 ret = -1;
1294 else if (info_od->wxflag & WX_OPEN)
1296 HANDLE handle;
1298 if (DuplicateHandle(GetCurrentProcess(), info_od->handle,
1299 GetCurrentProcess(), &handle, 0, TRUE, DUPLICATE_SAME_ACCESS))
1301 int wxflag = info_od->wxflag & ~WX_DONTINHERIT;
1303 if (info_nd->wxflag & WX_OPEN)
1304 _close(nd);
1306 msvcrt_set_fd(info_nd, handle, wxflag);
1307 /* _dup2 returns 0, not nd, on success */
1308 ret = 0;
1310 else
1312 ret = -1;
1313 msvcrt_set_errno(GetLastError());
1316 else
1318 *_errno() = EBADF;
1319 ret = -1;
1322 release_ioinfo(info_od);
1323 release_ioinfo(info_nd);
1324 return ret;
1327 /*********************************************************************
1328 * _dup (MSVCRT.@)
1330 int CDECL _dup(int od)
1332 int fd, ret;
1333 ioinfo *info = get_ioinfo_alloc(&fd);
1335 if (_dup2(od, fd) == 0)
1336 ret = fd;
1337 else
1338 ret = -1;
1339 release_ioinfo(info);
1340 return ret;
1343 /*********************************************************************
1344 * _eof (MSVCRT.@)
1346 int CDECL _eof(int fd)
1348 ioinfo *info = get_ioinfo(fd);
1349 DWORD curpos,endpos;
1350 LONG hcurpos,hendpos;
1352 TRACE(":fd (%d) handle (%p)\n", fd, info->handle);
1354 if (info->handle == INVALID_HANDLE_VALUE)
1356 release_ioinfo(info);
1357 return -1;
1360 if (info->wxflag & WX_ATEOF)
1362 release_ioinfo(info);
1363 return TRUE;
1366 /* Otherwise we do it the hard way */
1367 hcurpos = hendpos = 0;
1368 curpos = SetFilePointer(info->handle, 0, &hcurpos, FILE_CURRENT);
1369 endpos = SetFilePointer(info->handle, 0, &hendpos, FILE_END);
1371 if (curpos == endpos && hcurpos == hendpos)
1373 /* FIXME: shouldn't WX_ATEOF be set here? */
1374 release_ioinfo(info);
1375 return TRUE;
1378 SetFilePointer(info->handle, curpos, &hcurpos, FILE_BEGIN);
1379 release_ioinfo(info);
1380 return FALSE;
1383 /*********************************************************************
1384 * _fcloseall (MSVCRT.@)
1386 int CDECL _fcloseall(void)
1388 int num_closed = 0, i;
1389 FILE *file;
1391 LOCK_FILES();
1392 for (i = 3; i < MSVCRT_stream_idx; i++) {
1393 file = msvcrt_get_file(i);
1395 if (file->_flag && !fclose(file))
1396 num_closed++;
1398 UNLOCK_FILES();
1400 TRACE(":closed (%d) handles\n",num_closed);
1401 return num_closed;
1404 /* free everything on process exit */
1405 void msvcrt_free_io(void)
1407 unsigned int i;
1408 int j;
1410 _flushall();
1411 _fcloseall();
1413 for(i=0; i<ARRAY_SIZE(MSVCRT___pioinfo); i++)
1415 if(!MSVCRT___pioinfo[i])
1416 continue;
1418 for(j=0; j<MSVCRT_FD_BLOCK_SIZE; j++)
1420 if(ioinfo_is_crit_init(&MSVCRT___pioinfo[i][j]))
1421 DeleteCriticalSection(&MSVCRT___pioinfo[i][j].crit);
1423 free(MSVCRT___pioinfo[i]);
1426 for(j=0; j<MSVCRT_stream_idx; j++)
1428 FILE *file = msvcrt_get_file(j);
1429 CRITICAL_SECTION *cs = file_get_cs(file);
1431 if(cs)
1433 cs->DebugInfo->Spare[0] = 0;
1434 DeleteCriticalSection(cs);
1438 for(i=0; i<ARRAY_SIZE(MSVCRT_fstream); i++)
1439 free(MSVCRT_fstream[i]);
1442 /*********************************************************************
1443 * _lseeki64 (MSVCRT.@)
1445 __int64 CDECL _lseeki64(int fd, __int64 offset, int whence)
1447 ioinfo *info = get_ioinfo(fd);
1448 LARGE_INTEGER ofs;
1450 TRACE(":fd (%d) handle (%p)\n", fd, info->handle);
1452 if (info->handle == INVALID_HANDLE_VALUE)
1454 *_errno() = EBADF;
1455 release_ioinfo(info);
1456 return -1;
1459 if (whence < 0 || whence > 2)
1461 release_ioinfo(info);
1462 *_errno() = EINVAL;
1463 return -1;
1466 TRACE(":fd (%d) to %#I64x pos %s\n",
1467 fd, offset, (whence == SEEK_SET) ? "SEEK_SET" :
1468 (whence == SEEK_CUR) ? "SEEK_CUR" :
1469 (whence == SEEK_END) ? "SEEK_END" : "UNKNOWN");
1471 /* The MoleBox protection scheme expects msvcrt to use SetFilePointer only,
1472 * so a LARGE_INTEGER offset cannot be passed directly via SetFilePointerEx. */
1473 ofs.QuadPart = offset;
1474 if ((ofs.u.LowPart = SetFilePointer(info->handle, ofs.u.LowPart, &ofs.u.HighPart, whence)) != INVALID_SET_FILE_POINTER ||
1475 GetLastError() == ERROR_SUCCESS)
1477 info->wxflag &= ~WX_ATEOF;
1478 /* FIXME: What if we seek _to_ EOF - is EOF set? */
1480 release_ioinfo(info);
1481 return ofs.QuadPart;
1483 release_ioinfo(info);
1484 TRACE(":error-last error (%ld)\n", GetLastError());
1485 msvcrt_set_errno(GetLastError());
1486 return -1;
1489 /*********************************************************************
1490 * _lseek (MSVCRT.@)
1492 __msvcrt_long CDECL _lseek(int fd, __msvcrt_long offset, int whence)
1494 return _lseeki64(fd, offset, whence);
1497 /*********************************************************************
1498 * _lock_file (MSVCRT.@)
1500 void CDECL _lock_file(FILE *file)
1502 CRITICAL_SECTION *cs = file_get_cs(file);
1503 if (!cs)
1504 _lock(_STREAM_LOCKS + (file - iob_get_file(0)));
1505 else
1506 EnterCriticalSection(cs);
1509 /*********************************************************************
1510 * _unlock_file (MSVCRT.@)
1512 void CDECL _unlock_file(FILE *file)
1514 CRITICAL_SECTION *cs = file_get_cs(file);
1515 if (!cs)
1516 _unlock(_STREAM_LOCKS + (file - iob_get_file(0)));
1517 else
1518 LeaveCriticalSection(cs);
1521 /*********************************************************************
1522 * _locking (MSVCRT.@)
1524 * This is untested; the underlying LockFile doesn't work yet.
1526 int CDECL _locking(int fd, int mode, __msvcrt_long nbytes)
1528 ioinfo *info = get_ioinfo(fd);
1529 BOOL ret;
1530 DWORD cur_locn;
1532 TRACE(":fd (%d) handle (%p)\n", fd, info->handle);
1533 if (info->handle == INVALID_HANDLE_VALUE)
1535 release_ioinfo(info);
1536 return -1;
1539 if (mode < 0 || mode > 4)
1541 release_ioinfo(info);
1542 *_errno() = EINVAL;
1543 return -1;
1546 TRACE(":fd (%d) by %#lx mode %s\n",
1547 fd, nbytes, (mode == _LK_UNLCK) ? "_LK_UNLCK" :
1548 (mode == _LK_LOCK) ? "_LK_LOCK" :
1549 (mode == _LK_NBLCK) ? "_LK_NBLCK" :
1550 (mode == _LK_RLCK) ? "_LK_RLCK" :
1551 (mode == _LK_NBRLCK) ? "_LK_NBRLCK" :
1552 "UNKNOWN");
1554 if ((cur_locn = SetFilePointer(info->handle, 0L, NULL, FILE_CURRENT)) == INVALID_SET_FILE_POINTER)
1556 release_ioinfo(info);
1557 FIXME("Seek failed\n");
1558 *_errno() = EINVAL; /* FIXME */
1559 return -1;
1561 if (mode == _LK_LOCK || mode == _LK_RLCK)
1563 int nretry = 10;
1564 ret = 1; /* just to satisfy gcc */
1565 while (nretry--)
1567 ret = LockFile(info->handle, cur_locn, 0L, nbytes, 0L);
1568 if (ret) break;
1569 Sleep(1);
1572 else if (mode == _LK_UNLCK)
1573 ret = UnlockFile(info->handle, cur_locn, 0L, nbytes, 0L);
1574 else
1575 ret = LockFile(info->handle, cur_locn, 0L, nbytes, 0L);
1576 /* FIXME - what about error settings? */
1577 release_ioinfo(info);
1578 return ret ? 0 : -1;
1581 /*********************************************************************
1582 * _fseeki64 (MSVCRT.@)
1584 int CDECL _fseeki64(FILE* file, __int64 offset, int whence)
1586 int ret;
1588 _lock_file(file);
1589 ret = _fseeki64_nolock(file, offset, whence);
1590 _unlock_file(file);
1592 return ret;
1595 /*********************************************************************
1596 * _fseeki64_nolock (MSVCRT.@)
1598 int CDECL _fseeki64_nolock(FILE* file, __int64 offset, int whence)
1600 int ret;
1602 if(whence == SEEK_CUR && file->_flag & _IOREAD ) {
1603 whence = SEEK_SET;
1604 offset += _ftelli64_nolock(file);
1607 /* Flush output if needed */
1608 msvcrt_flush_buffer(file);
1609 /* Reset direction of i/o */
1610 if(file->_flag & _IORW) {
1611 file->_flag &= ~(_IOREAD|_IOWRT);
1613 /* Clear end of file flag */
1614 file->_flag &= ~_IOEOF;
1615 ret = (_lseeki64(file->_file,offset,whence) == -1)?-1:0;
1617 return ret;
1620 /*********************************************************************
1621 * fseek (MSVCRT.@)
1623 int CDECL fseek(FILE* file, __msvcrt_long offset, int whence)
1625 return _fseeki64( file, offset, whence );
1628 /*********************************************************************
1629 * _fseek_nolock (MSVCRT.@)
1631 int CDECL _fseek_nolock(FILE* file, __msvcrt_long offset, int whence)
1633 return _fseeki64_nolock( file, offset, whence );
1636 /*********************************************************************
1637 * _chsize_s (MSVCRT.@)
1639 int CDECL _chsize_s(int fd, __int64 size)
1641 ioinfo *info;
1642 __int64 cur, pos;
1643 BOOL ret = FALSE;
1645 TRACE("(fd=%d, size=%#I64x)\n", fd, size);
1647 if (!MSVCRT_CHECK_PMT(size >= 0)) return EINVAL;
1650 info = get_ioinfo(fd);
1651 if (info->handle != INVALID_HANDLE_VALUE)
1653 /* save the current file pointer */
1654 cur = _lseeki64(fd, 0, SEEK_CUR);
1655 if (cur >= 0)
1657 pos = _lseeki64(fd, size, SEEK_SET);
1658 if (pos >= 0)
1660 ret = SetEndOfFile(info->handle);
1661 if (!ret) msvcrt_set_errno(GetLastError());
1664 /* restore the file pointer */
1665 _lseeki64(fd, cur, SEEK_SET);
1669 release_ioinfo(info);
1670 return ret ? 0 : *_errno();
1673 /*********************************************************************
1674 * _chsize (MSVCRT.@)
1676 int CDECL _chsize(int fd, __msvcrt_long size)
1678 /* _chsize_s returns errno on failure but _chsize should return -1 */
1679 return _chsize_s( fd, size ) == 0 ? 0 : -1;
1682 /*********************************************************************
1683 * clearerr (MSVCRT.@)
1685 void CDECL clearerr(FILE* file)
1687 TRACE(":file (%p) fd (%d)\n",file,file->_file);
1689 _lock_file(file);
1690 file->_flag &= ~(_IOERR | _IOEOF);
1691 _unlock_file(file);
1694 /*********************************************************************
1695 * clearerr_s (MSVCRT.@)
1697 int CDECL clearerr_s(FILE* file)
1699 TRACE(":file (%p)\n",file);
1701 if (!MSVCRT_CHECK_PMT(file != NULL)) return EINVAL;
1703 _lock_file(file);
1704 file->_flag &= ~(_IOERR | _IOEOF);
1705 _unlock_file(file);
1706 return 0;
1709 #if defined(__i386__)
1710 /* Stack preserving thunk for rewind
1711 * needed for the UIO mod for Fallout: New Vegas
1713 __ASM_GLOBAL_FUNC(rewind_preserve_stack,
1714 "pushl 4(%esp)\n\t"
1715 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
1716 "call "__ASM_NAME("rewind") "\n\t"
1717 "addl $4,%esp\n\t"
1718 __ASM_CFI(".cfi_adjust_cfa_offset -4\n\t")
1719 "ret")
1720 #endif
1722 /*********************************************************************
1723 * rewind (MSVCRT.@)
1725 void CDECL rewind(FILE* file)
1727 TRACE(":file (%p) fd (%d)\n",file,file->_file);
1729 _lock_file(file);
1730 _fseek_nolock(file, 0L, SEEK_SET);
1731 clearerr(file);
1732 _unlock_file(file);
1735 static int msvcrt_get_flags(const wchar_t* mode, int *open_flags, int* stream_flags)
1737 int plus = wcschr(mode, '+') != NULL;
1739 TRACE("%s\n", debugstr_w(mode));
1741 while(*mode == ' ') mode++;
1743 switch(*mode++)
1745 case 'R': case 'r':
1746 *open_flags = plus ? _O_RDWR : _O_RDONLY;
1747 *stream_flags = plus ? _IORW : _IOREAD;
1748 break;
1749 case 'W': case 'w':
1750 *open_flags = _O_CREAT | _O_TRUNC | (plus ? _O_RDWR : _O_WRONLY);
1751 *stream_flags = plus ? _IORW : _IOWRT;
1752 break;
1753 case 'A': case 'a':
1754 *open_flags = _O_CREAT | _O_APPEND | (plus ? _O_RDWR : _O_WRONLY);
1755 *stream_flags = plus ? _IORW : _IOWRT;
1756 break;
1757 default:
1758 MSVCRT_INVALID_PMT(0, EINVAL);
1759 return -1;
1762 *stream_flags |= MSVCRT__commode;
1764 while (*mode && *mode!=',')
1765 switch (*mode++)
1767 case 'B': case 'b':
1768 *open_flags |= _O_BINARY;
1769 *open_flags &= ~_O_TEXT;
1770 break;
1771 case 't':
1772 *open_flags |= _O_TEXT;
1773 *open_flags &= ~_O_BINARY;
1774 break;
1775 #if _MSVCR_VER>=140
1776 case 'x':
1777 if(!MSVCRT_CHECK_PMT((*open_flags & (_O_CREAT | _O_APPEND)) == _O_CREAT))
1778 return -1;
1779 *open_flags |= _O_EXCL;
1780 break;
1781 #endif
1782 case 'D':
1783 *open_flags |= _O_TEMPORARY;
1784 break;
1785 case 'T':
1786 *open_flags |= _O_SHORT_LIVED;
1787 break;
1788 case 'c':
1789 *stream_flags |= MSVCRT__IOCOMMIT;
1790 break;
1791 case 'n':
1792 *stream_flags &= ~MSVCRT__IOCOMMIT;
1793 break;
1794 case 'N':
1795 *open_flags |= _O_NOINHERIT;
1796 break;
1797 case '+':
1798 case ' ':
1799 case 'a':
1800 case 'w':
1801 break;
1802 case 'S':
1803 if (!(*open_flags & _O_RANDOM))
1804 *open_flags |= _O_SEQUENTIAL;
1805 break;
1806 case 'R':
1807 if (!(*open_flags & _O_SEQUENTIAL))
1808 *open_flags |= _O_RANDOM;
1809 break;
1810 default:
1811 ERR("incorrect mode flag: %c\n", mode[-1]);
1812 break;
1815 if(*mode == ',')
1817 mode++;
1818 while(*mode == ' ') mode++;
1819 if(!MSVCRT_CHECK_PMT(!wcsncmp(L"ccs", mode, 3)))
1820 return -1;
1821 mode += 3;
1822 while(*mode == ' ') mode++;
1823 if(!MSVCRT_CHECK_PMT(*mode == '='))
1824 return -1;
1825 mode++;
1826 while(*mode == ' ') mode++;
1828 if(!_wcsnicmp(L"utf-8", mode, 5))
1830 *open_flags |= _O_U8TEXT;
1831 mode += 5;
1833 else if(!_wcsnicmp(L"utf-16le", mode, 8))
1835 *open_flags |= _O_U16TEXT;
1836 mode += 8;
1838 else if(!_wcsnicmp(L"unicode", mode, 7))
1840 *open_flags |= _O_WTEXT;
1841 mode += 7;
1843 else
1845 MSVCRT_INVALID_PMT(0, EINVAL);
1846 return -1;
1849 while(*mode == ' ') mode++;
1852 if(!MSVCRT_CHECK_PMT(*mode == 0))
1853 return -1;
1854 return 0;
1857 /*********************************************************************
1858 * _fdopen (MSVCRT.@)
1860 FILE* CDECL _fdopen(int fd, const char *mode)
1862 FILE *ret;
1863 wchar_t *modeW = NULL;
1865 if (mode && !(modeW = msvcrt_wstrdupa(mode))) return NULL;
1867 ret = _wfdopen(fd, modeW);
1869 free(modeW);
1870 return ret;
1873 /*********************************************************************
1874 * _wfdopen (MSVCRT.@)
1876 FILE* CDECL _wfdopen(int fd, const wchar_t *mode)
1878 int open_flags, stream_flags;
1879 FILE* file;
1881 if (msvcrt_get_flags(mode, &open_flags, &stream_flags) == -1) return NULL;
1883 LOCK_FILES();
1884 if (!(file = msvcrt_alloc_fp()))
1885 file = NULL;
1886 else if (msvcrt_init_fp(file, fd, stream_flags) == -1)
1888 file->_flag = 0;
1889 file = NULL;
1891 else TRACE(":fd (%d) mode (%s) FILE* (%p)\n", fd, debugstr_w(mode), file);
1892 UNLOCK_FILES();
1894 return file;
1897 /*********************************************************************
1898 * _filelength (MSVCRT.@)
1900 __msvcrt_long CDECL _filelength(int fd)
1902 LONG curPos = _lseek(fd, 0, SEEK_CUR);
1903 if (curPos != -1)
1905 LONG endPos = _lseek(fd, 0, SEEK_END);
1906 if (endPos != -1)
1908 if (endPos != curPos)
1909 _lseek(fd, curPos, SEEK_SET);
1910 return endPos;
1913 return -1;
1916 /*********************************************************************
1917 * _filelengthi64 (MSVCRT.@)
1919 __int64 CDECL _filelengthi64(int fd)
1921 __int64 curPos = _lseeki64(fd, 0, SEEK_CUR);
1922 if (curPos != -1)
1924 __int64 endPos = _lseeki64(fd, 0, SEEK_END);
1925 if (endPos != -1)
1927 if (endPos != curPos)
1928 _lseeki64(fd, curPos, SEEK_SET);
1929 return endPos;
1932 return -1;
1935 /*********************************************************************
1936 * _fileno (MSVCRT.@)
1938 int CDECL _fileno(FILE* file)
1940 TRACE(":FILE* (%p) fd (%d)\n",file,file->_file);
1941 return file->_file;
1944 /*********************************************************************
1945 * _fstat64 (MSVCRT.@)
1947 int CDECL _fstat64(int fd, struct _stat64* buf)
1949 ioinfo *info = get_ioinfo(fd);
1950 DWORD dw;
1951 DWORD type;
1953 TRACE(":fd (%d) stat (%p)\n", fd, buf);
1954 if (info->handle == INVALID_HANDLE_VALUE)
1956 release_ioinfo(info);
1957 return -1;
1960 if (!buf)
1962 WARN(":failed-NULL buf\n");
1963 msvcrt_set_errno(ERROR_INVALID_PARAMETER);
1964 release_ioinfo(info);
1965 return -1;
1968 memset(buf, 0, sizeof(struct _stat64));
1969 type = GetFileType(info->handle);
1970 if (type == FILE_TYPE_PIPE)
1972 buf->st_dev = buf->st_rdev = fd;
1973 buf->st_mode = _S_IFIFO;
1974 buf->st_nlink = 1;
1976 else if (type == FILE_TYPE_CHAR)
1978 buf->st_dev = buf->st_rdev = fd;
1979 buf->st_mode = _S_IFCHR;
1980 buf->st_nlink = 1;
1982 else /* FILE_TYPE_DISK etc. */
1984 FILE_BASIC_INFORMATION basic_info;
1985 FILE_STANDARD_INFORMATION std_info;
1986 IO_STATUS_BLOCK io;
1987 NTSTATUS status;
1989 if ((status = NtQueryInformationFile( info->handle, &io, &basic_info, sizeof(basic_info), FileBasicInformation )) ||
1990 (status = NtQueryInformationFile( info->handle, &io, &std_info, sizeof(std_info), FileStandardInformation )))
1992 WARN(":failed-error %lx\n", status);
1993 msvcrt_set_errno(ERROR_INVALID_PARAMETER);
1994 release_ioinfo(info);
1995 return -1;
1997 buf->st_mode = _S_IFREG | 0444;
1998 if (!(basic_info.FileAttributes & FILE_ATTRIBUTE_READONLY))
1999 buf->st_mode |= 0222;
2000 buf->st_size = std_info.EndOfFile.QuadPart;
2001 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&basic_info.LastAccessTime, &dw);
2002 buf->st_atime = dw;
2003 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&basic_info.LastWriteTime, &dw);
2004 buf->st_mtime = buf->st_ctime = dw;
2005 buf->st_nlink = std_info.NumberOfLinks;
2006 TRACE(":dwFileAttributes = %#lx, mode set to %#x\n",
2007 basic_info.FileAttributes, buf->st_mode);
2009 release_ioinfo(info);
2010 return 0;
2013 /*********************************************************************
2014 * _fstati64 (MSVCRT.@)
2016 int CDECL _fstati64(int fd, struct _stati64* buf)
2018 int ret;
2019 struct _stat64 buf64;
2021 ret = _fstat64(fd, &buf64);
2022 if (!ret)
2023 msvcrt_stat64_to_stati64(&buf64, buf);
2024 return ret;
2027 /*********************************************************************
2028 * _fstat (MSVCRT.@)
2030 int CDECL _fstat(int fd, struct _stat* buf)
2031 { int ret;
2032 struct _stat64 buf64;
2034 ret = _fstat64(fd, &buf64);
2035 if (!ret)
2036 msvcrt_stat64_to_stat(&buf64, buf);
2037 return ret;
2040 /*********************************************************************
2041 * _fstat32 (MSVCR80.@)
2043 int CDECL _fstat32(int fd, struct _stat32* buf)
2045 int ret;
2046 struct _stat64 buf64;
2048 ret = _fstat64(fd, &buf64);
2049 if (!ret)
2050 msvcrt_stat64_to_stat32(&buf64, buf);
2051 return ret;
2054 /*********************************************************************
2055 * _fstat32i64 (MSVCR80.@)
2057 int CDECL _fstat32i64(int fd, struct _stat32i64* buf)
2059 int ret;
2060 struct _stat64 buf64;
2062 ret = _fstat64(fd, &buf64);
2063 if (!ret)
2064 msvcrt_stat64_to_stat32i64(&buf64, buf);
2065 return ret;
2068 /*********************************************************************
2069 * _fstat64i32 (MSVCR80.@)
2071 int CDECL _fstat64i32(int fd, struct _stat64i32* buf)
2073 int ret;
2074 struct _stat64 buf64;
2076 ret = _fstat64(fd, &buf64);
2077 if (!ret)
2078 msvcrt_stat64_to_stat64i32(&buf64, buf);
2079 return ret;
2082 /*********************************************************************
2083 * _futime64 (MSVCRT.@)
2085 int CDECL _futime64(int fd, struct __utimbuf64 *t)
2087 ioinfo *info = get_ioinfo(fd);
2088 FILETIME at, wt;
2090 if (!t)
2092 time_to_filetime( _time64(NULL), &at );
2093 wt = at;
2095 else
2097 time_to_filetime( t->actime, &at );
2098 time_to_filetime( t->modtime, &wt );
2101 if (!SetFileTime(info->handle, NULL, &at, &wt))
2103 release_ioinfo(info);
2104 msvcrt_set_errno(GetLastError());
2105 return -1 ;
2107 release_ioinfo(info);
2108 return 0;
2111 /*********************************************************************
2112 * _futime32 (MSVCRT.@)
2114 int CDECL _futime32(int fd, struct __utimbuf32 *t)
2116 if (t)
2118 struct __utimbuf64 t64;
2119 t64.actime = t->actime;
2120 t64.modtime = t->modtime;
2121 return _futime64( fd, &t64 );
2123 else
2124 return _futime64( fd, NULL );
2127 /*********************************************************************
2128 * _get_osfhandle (MSVCRT.@)
2130 intptr_t CDECL _get_osfhandle(int fd)
2132 HANDLE hand = get_ioinfo_nolock(fd)->handle;
2133 TRACE(":fd (%d) handle (%p)\n",fd,hand);
2135 if(hand == INVALID_HANDLE_VALUE)
2136 *_errno() = EBADF;
2137 return (intptr_t)hand;
2140 /*********************************************************************
2141 * _mktemp_s (MSVCRT.@)
2143 int CDECL _mktemp_s(char *pattern, size_t size)
2145 DWORD len, xno, id;
2147 if(!MSVCRT_CHECK_PMT(pattern!=NULL))
2148 return EINVAL;
2150 for(len=0; len<size; len++)
2151 if(!pattern[len])
2152 break;
2153 if(!MSVCRT_CHECK_PMT(len!=size && len>=6)) {
2154 if(size)
2155 pattern[0] = 0;
2156 return EINVAL;
2159 for(xno=1; xno<=6; xno++)
2160 if(!MSVCRT_CHECK_PMT(pattern[len-xno] == 'X'))
2161 return EINVAL;
2163 id = GetCurrentProcessId();
2164 for(xno=1; xno<6; xno++) {
2165 pattern[len-xno] = id%10 + '0';
2166 id /= 10;
2169 for(pattern[len-6]='a'; pattern[len-6]<='z'; pattern[len-6]++) {
2170 if(GetFileAttributesA(pattern) == INVALID_FILE_ATTRIBUTES)
2171 return 0;
2174 pattern[0] = 0;
2175 *_errno() = EEXIST;
2176 return EEXIST;
2179 /*********************************************************************
2180 * _mktemp (MSVCRT.@)
2182 char * CDECL _mktemp(char *pattern)
2184 int numX = 0;
2185 char *retVal = pattern;
2186 int id;
2187 char letter = 'a';
2189 if(!pattern)
2190 return NULL;
2192 while(*pattern)
2193 numX = (*pattern++ == 'X')? numX + 1 : 0;
2194 if (numX < 6)
2195 return NULL;
2196 pattern--;
2197 id = GetCurrentProcessId();
2198 numX = 6;
2199 while(numX--)
2201 int tempNum = id / 10;
2202 *pattern-- = id - (tempNum * 10) + '0';
2203 id = tempNum;
2205 pattern++;
2208 *pattern = letter++;
2209 if (GetFileAttributesA(retVal) == INVALID_FILE_ATTRIBUTES)
2210 return retVal;
2211 } while(letter <= 'z');
2212 return NULL;
2215 /*********************************************************************
2216 * _wmktemp_s (MSVCRT.@)
2218 int CDECL _wmktemp_s(wchar_t *pattern, size_t size)
2220 DWORD len, xno, id;
2222 if(!MSVCRT_CHECK_PMT(pattern!=NULL))
2223 return EINVAL;
2225 for(len=0; len<size; len++)
2226 if(!pattern[len])
2227 break;
2228 if(!MSVCRT_CHECK_PMT(len!=size && len>=6)) {
2229 if(size)
2230 pattern[0] = 0;
2231 return EINVAL;
2234 for(xno=1; xno<=6; xno++)
2235 if(!MSVCRT_CHECK_PMT(pattern[len-xno] == 'X'))
2236 return EINVAL;
2238 id = GetCurrentProcessId();
2239 for(xno=1; xno<6; xno++) {
2240 pattern[len-xno] = id%10 + '0';
2241 id /= 10;
2244 for(pattern[len-6]='a'; pattern[len-6]<='z'; pattern[len-6]++) {
2245 if(GetFileAttributesW(pattern) == INVALID_FILE_ATTRIBUTES)
2246 return 0;
2249 pattern[0] = 0;
2250 *_errno() = EEXIST;
2251 return EEXIST;
2254 /*********************************************************************
2255 * _wmktemp (MSVCRT.@)
2257 wchar_t * CDECL _wmktemp(wchar_t *pattern)
2259 int numX = 0;
2260 wchar_t *retVal = pattern;
2261 int id;
2262 wchar_t letter = 'a';
2264 if(!pattern)
2265 return NULL;
2267 while(*pattern)
2268 numX = (*pattern++ == 'X')? numX + 1 : 0;
2269 if (numX < 6)
2270 return NULL;
2271 pattern--;
2272 id = GetCurrentProcessId();
2273 numX = 6;
2274 while(numX--)
2276 int tempNum = id / 10;
2277 *pattern-- = id - (tempNum * 10) + '0';
2278 id = tempNum;
2280 pattern++;
2283 if (GetFileAttributesW(retVal) == INVALID_FILE_ATTRIBUTES)
2284 return retVal;
2285 *pattern = letter++;
2286 } while(letter != '|');
2287 return NULL;
2290 static unsigned split_oflags(unsigned oflags)
2292 int wxflags = 0;
2293 unsigned unsupp; /* until we support everything */
2295 if (oflags & _O_APPEND) wxflags |= WX_APPEND;
2296 if (oflags & _O_BINARY) {/* Nothing to do */}
2297 else if (oflags & _O_TEXT) wxflags |= WX_TEXT;
2298 else if (oflags & _O_WTEXT) wxflags |= WX_TEXT;
2299 else if (oflags & _O_U16TEXT) wxflags |= WX_TEXT;
2300 else if (oflags & _O_U8TEXT) wxflags |= WX_TEXT;
2301 else
2303 int fmode;
2304 _get_fmode(&fmode);
2305 if (!(fmode & _O_BINARY)) wxflags |= WX_TEXT; /* default to TEXT*/
2307 if (oflags & _O_NOINHERIT) wxflags |= WX_DONTINHERIT;
2309 if ((unsupp = oflags & ~(_O_BINARY | _O_TEXT | _O_APPEND | _O_TRUNC | _O_EXCL | _O_CREAT |
2310 _O_RDWR | _O_WRONLY | _O_TEMPORARY | _O_NOINHERIT | _O_SEQUENTIAL |
2311 _O_RANDOM | _O_SHORT_LIVED | _O_WTEXT | _O_U16TEXT | _O_U8TEXT)))
2312 ERR(":unsupported oflags %#x\n",unsupp);
2314 return wxflags;
2317 /*********************************************************************
2318 * _pipe (MSVCRT.@)
2320 int CDECL _pipe(int *pfds, unsigned int psize, int textmode)
2322 int ret = -1;
2323 SECURITY_ATTRIBUTES sa;
2324 HANDLE readHandle, writeHandle;
2326 if (!pfds)
2328 *_errno() = EINVAL;
2329 return -1;
2332 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
2333 sa.bInheritHandle = !(textmode & _O_NOINHERIT);
2334 sa.lpSecurityDescriptor = NULL;
2335 if (CreatePipe(&readHandle, &writeHandle, &sa, psize))
2337 unsigned int wxflags = split_oflags(textmode);
2338 int fd;
2340 fd = msvcrt_alloc_fd(readHandle, wxflags|WX_PIPE);
2341 if (fd != -1)
2343 pfds[0] = fd;
2344 fd = msvcrt_alloc_fd(writeHandle, wxflags|WX_PIPE);
2345 if (fd != -1)
2347 pfds[1] = fd;
2348 ret = 0;
2350 else
2352 _close(pfds[0]);
2353 CloseHandle(writeHandle);
2354 *_errno() = EMFILE;
2357 else
2359 CloseHandle(readHandle);
2360 CloseHandle(writeHandle);
2361 *_errno() = EMFILE;
2364 else
2365 msvcrt_set_errno(GetLastError());
2367 return ret;
2370 static int check_bom(HANDLE h, int oflags, BOOL seek)
2372 char bom[sizeof(utf8_bom)];
2373 DWORD r;
2375 if (!ReadFile(h, bom, sizeof(utf8_bom), &r, NULL))
2376 return oflags;
2378 if (r==sizeof(utf8_bom) && !memcmp(bom, utf8_bom, sizeof(utf8_bom))) {
2379 oflags = (oflags & ~(_O_WTEXT | _O_U16TEXT)) | _O_U8TEXT;
2380 }else if (r>=sizeof(utf16_bom) && !memcmp(bom, utf16_bom, sizeof(utf16_bom))) {
2381 if (seek && r>2)
2382 SetFilePointer(h, 2, NULL, FILE_BEGIN);
2383 oflags = (oflags & ~(_O_WTEXT | _O_U8TEXT)) | _O_U16TEXT;
2384 }else if (seek) {
2385 SetFilePointer(h, 0, NULL, FILE_BEGIN);
2388 return oflags;
2391 /*********************************************************************
2392 * _wsopen_dispatch (UCRTBASE.@)
2394 int CDECL _wsopen_dispatch( const wchar_t* path, int oflags, int shflags, int pmode,
2395 int *fd, int secure )
2397 DWORD access = 0, creation = 0, attrib;
2398 SECURITY_ATTRIBUTES sa;
2399 DWORD sharing, type;
2400 int wxflag;
2401 HANDLE hand;
2403 TRACE("path: (%s) oflags: %#x shflags: %#x pmode: %#x fd*: %p secure: %d\n",
2404 debugstr_w(path), oflags, shflags, pmode, fd, secure);
2406 if (!MSVCRT_CHECK_PMT( fd != NULL )) return EINVAL;
2408 *fd = -1;
2409 wxflag = split_oflags(oflags);
2410 switch (oflags & (_O_RDONLY | _O_WRONLY | _O_RDWR))
2412 case _O_RDONLY: access |= GENERIC_READ; break;
2413 case _O_WRONLY: access |= GENERIC_WRITE; break;
2414 case _O_RDWR: access |= GENERIC_WRITE | GENERIC_READ; break;
2417 if (oflags & _O_CREAT)
2419 if (secure && !MSVCRT_CHECK_PMT(!(pmode & ~(_S_IREAD | _S_IWRITE))))
2420 return EINVAL;
2422 if (oflags & _O_EXCL)
2423 creation = CREATE_NEW;
2424 else if (oflags & _O_TRUNC)
2425 creation = CREATE_ALWAYS;
2426 else
2427 creation = OPEN_ALWAYS;
2429 else /* no _O_CREAT */
2431 if (oflags & _O_TRUNC)
2432 creation = TRUNCATE_EXISTING;
2433 else
2434 creation = OPEN_EXISTING;
2437 switch( shflags )
2439 case _SH_DENYRW:
2440 sharing = 0L;
2441 break;
2442 case _SH_DENYWR:
2443 sharing = FILE_SHARE_READ;
2444 break;
2445 case _SH_DENYRD:
2446 sharing = FILE_SHARE_WRITE;
2447 break;
2448 case _SH_DENYNO:
2449 sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
2450 break;
2451 default:
2452 ERR( "Unhandled shflags %#x\n", shflags );
2453 return EINVAL;
2456 if (!(pmode & ~MSVCRT_umask & _S_IWRITE))
2457 attrib = FILE_ATTRIBUTE_READONLY;
2458 else
2459 attrib = FILE_ATTRIBUTE_NORMAL;
2461 if (oflags & _O_TEMPORARY)
2463 attrib |= FILE_FLAG_DELETE_ON_CLOSE;
2464 access |= DELETE;
2465 sharing |= FILE_SHARE_DELETE;
2468 if (oflags & _O_RANDOM)
2469 attrib |= FILE_FLAG_RANDOM_ACCESS;
2470 if (oflags & _O_SEQUENTIAL)
2471 attrib |= FILE_FLAG_SEQUENTIAL_SCAN;
2472 if (oflags & _O_SHORT_LIVED)
2473 attrib |= FILE_ATTRIBUTE_TEMPORARY;
2475 sa.nLength = sizeof( SECURITY_ATTRIBUTES );
2476 sa.lpSecurityDescriptor = NULL;
2477 sa.bInheritHandle = !(oflags & _O_NOINHERIT);
2479 if ((oflags & (_O_WTEXT | _O_U16TEXT | _O_U8TEXT))
2480 && (creation==OPEN_ALWAYS || creation==OPEN_EXISTING)
2481 && !(access&GENERIC_READ))
2483 hand = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE,
2484 &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
2485 if (hand != INVALID_HANDLE_VALUE)
2487 oflags = check_bom(hand, oflags, FALSE);
2488 CloseHandle(hand);
2492 hand = CreateFileW(path, access, sharing, &sa, creation, attrib, 0);
2493 if (hand == INVALID_HANDLE_VALUE) {
2494 WARN(":failed-last error (%ld)\n", GetLastError());
2495 msvcrt_set_errno(GetLastError());
2496 return *_errno();
2499 if (oflags & (_O_WTEXT | _O_U16TEXT | _O_U8TEXT))
2501 LARGE_INTEGER size = {{0}};
2503 if ((access & GENERIC_WRITE) && (creation==OPEN_EXISTING || creation==OPEN_ALWAYS))
2504 GetFileSizeEx(hand, &size);
2506 if ((access & GENERIC_WRITE) && (creation==CREATE_NEW
2507 || creation==CREATE_ALWAYS || creation==TRUNCATE_EXISTING
2508 || ((creation==OPEN_EXISTING || creation==OPEN_ALWAYS) && !size.QuadPart)))
2510 if (oflags & _O_U8TEXT)
2512 DWORD written = 0, tmp;
2514 while(written!=sizeof(utf8_bom) && WriteFile(hand, (char*)utf8_bom+written,
2515 sizeof(utf8_bom)-written, &tmp, NULL))
2516 written += tmp;
2517 if (written != sizeof(utf8_bom)) {
2518 WARN("error writing BOM\n");
2519 CloseHandle(hand);
2520 msvcrt_set_errno(GetLastError());
2521 return *_errno();
2524 else
2526 DWORD written = 0, tmp;
2528 while(written!=sizeof(utf16_bom) && WriteFile(hand, (char*)utf16_bom+written,
2529 sizeof(utf16_bom)-written, &tmp, NULL))
2530 written += tmp;
2531 if (written != sizeof(utf16_bom))
2533 WARN("error writing BOM\n");
2534 CloseHandle(hand);
2535 msvcrt_set_errno(GetLastError());
2536 return *_errno();
2538 oflags |= _O_U16TEXT;
2541 else if (access & GENERIC_READ)
2542 oflags = check_bom(hand, oflags, TRUE);
2545 type = GetFileType(hand);
2546 if (type == FILE_TYPE_CHAR)
2547 wxflag |= WX_TTY;
2548 else if (type == FILE_TYPE_PIPE)
2549 wxflag |= WX_PIPE;
2551 *fd = msvcrt_alloc_fd(hand, wxflag);
2552 if (*fd == -1)
2553 return *_errno();
2555 if (oflags & _O_WTEXT)
2556 ioinfo_set_unicode(get_ioinfo_nolock(*fd), TRUE);
2558 if (oflags & _O_U16TEXT)
2559 ioinfo_set_textmode(get_ioinfo_nolock(*fd), TEXTMODE_UTF16LE);
2560 else if (oflags & _O_U8TEXT)
2561 ioinfo_set_textmode(get_ioinfo_nolock(*fd), TEXTMODE_UTF8);
2563 TRACE(":fd (%d) handle (%p)\n", *fd, hand);
2564 return 0;
2568 /*********************************************************************
2569 * _wsopen_s (MSVCRT.@)
2571 int CDECL _wsopen_s( int *fd, const wchar_t* path, int oflags, int shflags, int pmode )
2573 return _wsopen_dispatch( path, oflags, shflags, pmode, fd, 1 );
2576 /*********************************************************************
2577 * _wsopen (MSVCRT.@)
2579 int WINAPIV _wsopen( const wchar_t *path, int oflags, int shflags, ... )
2581 int pmode;
2582 int fd;
2584 if (oflags & _O_CREAT)
2586 va_list ap;
2588 va_start(ap, shflags);
2589 pmode = va_arg(ap, int);
2590 va_end(ap);
2592 else
2593 pmode = 0;
2595 return _wsopen_dispatch(path, oflags, shflags, pmode, &fd, 0) ? -1 : fd;
2599 /*********************************************************************
2600 * _sopen_dispatch (UCRTBASE.@)
2602 int CDECL _sopen_dispatch( const char *path, int oflags, int shflags,
2603 int pmode, int *fd, int secure)
2605 wchar_t *pathW;
2606 int ret;
2608 if (!MSVCRT_CHECK_PMT(fd != NULL))
2609 return EINVAL;
2610 *fd = -1;
2611 if(!MSVCRT_CHECK_PMT(path && (pathW = msvcrt_wstrdupa(path))))
2612 return EINVAL;
2614 ret = _wsopen_dispatch(pathW, oflags, shflags, pmode, fd, secure);
2615 free(pathW);
2616 return ret;
2619 /*********************************************************************
2620 * _sopen_s (MSVCRT.@)
2622 int CDECL _sopen_s( int *fd, const char *path, int oflags, int shflags, int pmode )
2624 return _sopen_dispatch(path, oflags, shflags, pmode, fd, 1);
2627 /*********************************************************************
2628 * _sopen (MSVCRT.@)
2630 int WINAPIV _sopen( const char *path, int oflags, int shflags, ... )
2632 int pmode;
2633 int fd;
2635 if (oflags & _O_CREAT)
2637 va_list ap;
2639 va_start(ap, shflags);
2640 pmode = va_arg(ap, int);
2641 va_end(ap);
2643 else
2644 pmode = 0;
2646 return _sopen_dispatch(path, oflags, shflags, pmode, &fd, 0) ? -1 : fd;
2649 /*********************************************************************
2650 * _open (MSVCRT.@)
2652 int WINAPIV _open( const char *path, int flags, ... )
2654 va_list ap;
2656 if (flags & _O_CREAT)
2658 int pmode;
2659 va_start(ap, flags);
2660 pmode = va_arg(ap, int);
2661 va_end(ap);
2662 return _sopen( path, flags, _SH_DENYNO, pmode );
2664 else
2665 return _sopen( path, flags, _SH_DENYNO);
2668 /*********************************************************************
2669 * _wopen (MSVCRT.@)
2671 int WINAPIV _wopen(const wchar_t *path,int flags,...)
2673 va_list ap;
2675 if (flags & _O_CREAT)
2677 int pmode;
2678 va_start(ap, flags);
2679 pmode = va_arg(ap, int);
2680 va_end(ap);
2681 return _wsopen( path, flags, _SH_DENYNO, pmode );
2683 else
2684 return _wsopen( path, flags, _SH_DENYNO);
2687 /*********************************************************************
2688 * _creat (MSVCRT.@)
2690 int CDECL _creat(const char *path, int pmode)
2692 int flags = _O_CREAT | _O_TRUNC | _O_RDWR;
2693 return _open(path, flags, pmode);
2696 /*********************************************************************
2697 * _wcreat (MSVCRT.@)
2699 int CDECL _wcreat(const wchar_t *path, int pmode)
2701 int flags = _O_CREAT | _O_TRUNC | _O_RDWR;
2702 return _wopen(path, flags, pmode);
2705 /*********************************************************************
2706 * _open_osfhandle (MSVCRT.@)
2708 int CDECL _open_osfhandle(intptr_t handle, int oflags)
2710 DWORD flags;
2711 int fd;
2713 /* _O_RDONLY (0) always matches, so set the read flag
2714 * MFC's CStdioFile clears O_RDONLY (0)! if it wants to write to the
2715 * file, so set the write flag. It also only sets _O_TEXT if it wants
2716 * text - it never sets _O_BINARY.
2718 /* don't let split_oflags() decide the mode if no mode is passed */
2719 if (!(oflags & (_O_BINARY | _O_TEXT)))
2720 oflags |= _O_BINARY;
2722 flags = GetFileType((HANDLE)handle);
2723 if (flags==FILE_TYPE_UNKNOWN && GetLastError()!=NO_ERROR)
2725 msvcrt_set_errno(GetLastError());
2726 return -1;
2729 if (flags == FILE_TYPE_CHAR)
2730 flags = WX_TTY;
2731 else if (flags == FILE_TYPE_PIPE)
2732 flags = WX_PIPE;
2733 else
2734 flags = 0;
2735 flags |= split_oflags(oflags);
2737 fd = msvcrt_alloc_fd((HANDLE)handle, flags);
2738 TRACE(":handle (%Iu) fd (%d) flags %#lx\n", handle, fd, flags);
2739 return fd;
2742 /*********************************************************************
2743 * _rmtmp (MSVCRT.@)
2745 int CDECL _rmtmp(void)
2747 int num_removed = 0, i;
2748 FILE *file;
2750 LOCK_FILES();
2751 for (i = 3; i < MSVCRT_stream_idx; i++) {
2752 file = msvcrt_get_file(i);
2754 if (file->_tmpfname)
2756 fclose(file);
2757 num_removed++;
2760 UNLOCK_FILES();
2762 if (num_removed)
2763 TRACE(":removed (%d) temp files\n",num_removed);
2764 return num_removed;
2767 static inline int get_utf8_char_len(char ch)
2769 if((ch&0xf8) == 0xf0)
2770 return 4;
2771 else if((ch&0xf0) == 0xe0)
2772 return 3;
2773 else if((ch&0xe0) == 0xc0)
2774 return 2;
2775 return 1;
2778 /*********************************************************************
2779 * (internal) read_utf8
2781 static int read_utf8(ioinfo *fdinfo, wchar_t *buf, unsigned int count)
2783 HANDLE hand = fdinfo->handle;
2784 char min_buf[4], *readbuf, lookahead;
2785 DWORD readbuf_size, pos=0, num_read=1, char_len, i, j;
2787 /* make the buffer big enough to hold at least one character */
2788 /* read bytes have to fit to output and lookahead buffers */
2789 count /= 2;
2790 readbuf_size = count < 4 ? 4 : count;
2791 if(readbuf_size<=4 || !(readbuf = malloc(readbuf_size))) {
2792 readbuf_size = 4;
2793 readbuf = min_buf;
2796 if(fdinfo->lookahead[0] != '\n') {
2797 readbuf[pos++] = fdinfo->lookahead[0];
2798 fdinfo->lookahead[0] = '\n';
2800 if(fdinfo->lookahead[1] != '\n') {
2801 readbuf[pos++] = fdinfo->lookahead[1];
2802 fdinfo->lookahead[1] = '\n';
2804 if(fdinfo->lookahead[2] != '\n') {
2805 readbuf[pos++] = fdinfo->lookahead[2];
2806 fdinfo->lookahead[2] = '\n';
2811 /* NOTE: this case is broken in native dll, reading
2812 * sometimes fails when small buffer is passed
2814 if(count < 4) {
2815 if(!pos && !ReadFile(hand, readbuf, 1, &num_read, NULL)) {
2816 if (GetLastError() == ERROR_BROKEN_PIPE) {
2817 fdinfo->wxflag |= WX_ATEOF;
2818 return 0;
2819 }else {
2820 msvcrt_set_errno(GetLastError());
2821 if (GetLastError() == ERROR_ACCESS_DENIED)
2822 *_errno() = EBADF;
2823 return -1;
2825 }else if(!num_read) {
2826 fdinfo->wxflag |= WX_ATEOF;
2827 return 0;
2828 }else {
2829 pos++;
2832 char_len = get_utf8_char_len(readbuf[0]);
2833 if(char_len>pos) {
2834 if(ReadFile(hand, readbuf+pos, char_len-pos, &num_read, NULL))
2835 pos += num_read;
2838 if(readbuf[0] == '\n')
2839 fdinfo->wxflag |= WX_READNL;
2840 else
2841 fdinfo->wxflag &= ~WX_READNL;
2843 if(readbuf[0] == 0x1a) {
2844 fdinfo->wxflag |= WX_ATEOF;
2845 return 0;
2848 if(readbuf[0] == '\r') {
2849 if(!ReadFile(hand, &lookahead, 1, &num_read, NULL) || num_read!=1)
2850 buf[0] = '\r';
2851 else if(lookahead == '\n')
2852 buf[0] = '\n';
2853 else {
2854 buf[0] = '\r';
2855 if(fdinfo->wxflag & (WX_PIPE | WX_TTY))
2856 fdinfo->lookahead[0] = lookahead;
2857 else
2858 SetFilePointer(fdinfo->handle, -1, NULL, FILE_CURRENT);
2860 return 2;
2863 if(!(num_read = MultiByteToWideChar(CP_UTF8, 0, readbuf, pos, buf, count))) {
2864 msvcrt_set_errno(GetLastError());
2865 return -1;
2868 return num_read*2;
2871 if(!ReadFile(hand, readbuf+pos, readbuf_size-pos, &num_read, NULL)) {
2872 if(pos) {
2873 num_read = 0;
2874 }else if(GetLastError() == ERROR_BROKEN_PIPE) {
2875 fdinfo->wxflag |= WX_ATEOF;
2876 if (readbuf != min_buf) free(readbuf);
2877 return 0;
2878 }else {
2879 msvcrt_set_errno(GetLastError());
2880 if (GetLastError() == ERROR_ACCESS_DENIED)
2881 *_errno() = EBADF;
2882 if (readbuf != min_buf) free(readbuf);
2883 return -1;
2885 }else if(!pos && !num_read) {
2886 fdinfo->wxflag |= WX_ATEOF;
2887 if (readbuf != min_buf) free(readbuf);
2888 return 0;
2891 pos += num_read;
2892 if(readbuf[0] == '\n')
2893 fdinfo->wxflag |= WX_READNL;
2894 else
2895 fdinfo->wxflag &= ~WX_READNL;
2897 /* Find first byte of last character (may be incomplete) */
2898 for(i=pos-1; i>0 && i>pos-4; i--)
2899 if((readbuf[i]&0xc0) != 0x80)
2900 break;
2901 char_len = get_utf8_char_len(readbuf[i]);
2902 if(char_len+i <= pos)
2903 i += char_len;
2905 if(fdinfo->wxflag & (WX_PIPE | WX_TTY)) {
2906 if(i < pos)
2907 fdinfo->lookahead[0] = readbuf[i];
2908 if(i+1 < pos)
2909 fdinfo->lookahead[1] = readbuf[i+1];
2910 if(i+2 < pos)
2911 fdinfo->lookahead[2] = readbuf[i+2];
2912 }else if(i < pos) {
2913 SetFilePointer(fdinfo->handle, i-pos, NULL, FILE_CURRENT);
2915 pos = i;
2917 for(i=0, j=0; i<pos; i++) {
2918 if(readbuf[i] == 0x1a) {
2919 fdinfo->wxflag |= WX_ATEOF;
2920 break;
2923 /* strip '\r' if followed by '\n' */
2924 if(readbuf[i] == '\r' && i+1==pos) {
2925 if(fdinfo->lookahead[0] != '\n' || !ReadFile(hand, &lookahead, 1, &num_read, NULL) || !num_read) {
2926 readbuf[j++] = '\r';
2927 }else if(lookahead == '\n' && j==0) {
2928 readbuf[j++] = '\n';
2929 }else {
2930 if(lookahead != '\n')
2931 readbuf[j++] = '\r';
2933 if(fdinfo->wxflag & (WX_PIPE | WX_TTY))
2934 fdinfo->lookahead[0] = lookahead;
2935 else
2936 SetFilePointer(fdinfo->handle, -1, NULL, FILE_CURRENT);
2938 }else if(readbuf[i]!='\r' || readbuf[i+1]!='\n') {
2939 readbuf[j++] = readbuf[i];
2942 pos = j;
2944 if(!(num_read = MultiByteToWideChar(CP_UTF8, 0, readbuf, pos, buf, count))) {
2945 msvcrt_set_errno(GetLastError());
2946 if (readbuf != min_buf) free(readbuf);
2947 return -1;
2950 if (readbuf != min_buf) free(readbuf);
2951 return num_read*2;
2954 /*********************************************************************
2955 * (internal) read_i
2957 * When reading \r as last character in text mode, read() positions
2958 * the file pointer on the \r character while getc() goes on to
2959 * the following \n
2961 static int read_i(int fd, ioinfo *fdinfo, void *buf, unsigned int count)
2963 DWORD num_read, utf16;
2964 char *bufstart = buf;
2966 if (count == 0)
2967 return 0;
2969 if (fdinfo->wxflag & WX_ATEOF) {
2970 TRACE("already at EOF, returning 0\n");
2971 return 0;
2973 /* Don't trace small reads, it gets *very* annoying */
2974 if (count > 4)
2975 TRACE(":fd (%d) handle (%p) buf (%p) len (%d)\n", fd, fdinfo->handle, buf, count);
2976 if (fdinfo->handle == INVALID_HANDLE_VALUE)
2978 *_errno() = EBADF;
2979 return -1;
2982 utf16 = ioinfo_get_textmode(fdinfo) == TEXTMODE_UTF16LE;
2983 if (ioinfo_get_textmode(fdinfo) != TEXTMODE_ANSI && count&1)
2985 *_errno() = EINVAL;
2986 return -1;
2989 if((fdinfo->wxflag&WX_TEXT) && ioinfo_get_textmode(fdinfo) == TEXTMODE_UTF8)
2990 return read_utf8(fdinfo, buf, count);
2992 if (fdinfo->lookahead[0]!='\n' || ReadFile(fdinfo->handle, bufstart, count, &num_read, NULL))
2994 if (fdinfo->lookahead[0] != '\n')
2996 bufstart[0] = fdinfo->lookahead[0];
2997 fdinfo->lookahead[0] = '\n';
2999 if (utf16)
3001 bufstart[1] = fdinfo->lookahead[1];
3002 fdinfo->lookahead[1] = '\n';
3005 if(count>1+utf16 && ReadFile(fdinfo->handle, bufstart+1+utf16, count-1-utf16, &num_read, NULL))
3006 num_read += 1+utf16;
3007 else
3008 num_read = 1+utf16;
3011 if(utf16 && (num_read&1))
3013 /* msvcr90 uses uninitialized value from the buffer in this case */
3014 /* msvcrt ignores additional data */
3015 ERR("got odd number of bytes in UTF16 mode\n");
3016 num_read--;
3019 if (count != 0 && num_read == 0)
3021 fdinfo->wxflag |= WX_ATEOF;
3022 TRACE(":EOF %s\n",debugstr_an(buf,num_read));
3024 else if (fdinfo->wxflag & WX_TEXT)
3026 DWORD i, j;
3028 if (bufstart[0]=='\n' && (!utf16 || bufstart[1]==0))
3029 fdinfo->wxflag |= WX_READNL;
3030 else
3031 fdinfo->wxflag &= ~WX_READNL;
3033 for (i=0, j=0; i<num_read; i+=1+utf16)
3035 /* in text mode, a ctrl-z signals EOF */
3036 if (bufstart[i]==0x1a && (!utf16 || bufstart[i+1]==0))
3038 fdinfo->wxflag |= WX_ATEOF;
3039 TRACE(":^Z EOF %s\n",debugstr_an(buf,num_read));
3040 break;
3043 /* in text mode, strip \r if followed by \n */
3044 if (bufstart[i]=='\r' && (!utf16 || bufstart[i+1]==0) && i+1+utf16==num_read)
3046 char lookahead[2];
3047 DWORD len;
3049 lookahead[1] = '\n';
3050 if (ReadFile(fdinfo->handle, lookahead, 1+utf16, &len, NULL) && len)
3052 if(lookahead[0]=='\n' && (!utf16 || lookahead[1]==0) && j==0)
3054 bufstart[j++] = '\n';
3055 if(utf16) bufstart[j++] = 0;
3057 else
3059 if(lookahead[0]!='\n' || (utf16 && lookahead[1]!=0))
3061 bufstart[j++] = '\r';
3062 if(utf16) bufstart[j++] = 0;
3065 if (fdinfo->wxflag & (WX_PIPE | WX_TTY))
3067 if (lookahead[0]=='\n' && (!utf16 || !lookahead[1]))
3069 bufstart[j++] = '\n';
3070 if (utf16) bufstart[j++] = 0;
3072 else
3074 fdinfo->lookahead[0] = lookahead[0];
3075 fdinfo->lookahead[1] = lookahead[1];
3078 else
3079 SetFilePointer(fdinfo->handle, -1-utf16, NULL, FILE_CURRENT);
3082 else
3084 bufstart[j++] = '\r';
3085 if(utf16) bufstart[j++] = 0;
3088 else if((bufstart[i]!='\r' || (utf16 && bufstart[i+1]!=0))
3089 || (bufstart[i+1+utf16]!='\n' || (utf16 && bufstart[i+3]!=0)))
3091 bufstart[j++] = bufstart[i];
3092 if(utf16) bufstart[j++] = bufstart[i+1];
3095 num_read = j;
3098 else
3100 if (GetLastError() == ERROR_BROKEN_PIPE)
3102 TRACE(":end-of-pipe\n");
3103 fdinfo->wxflag |= WX_ATEOF;
3104 return 0;
3106 else
3108 TRACE(":failed-last error (%ld)\n", GetLastError());
3109 msvcrt_set_errno(GetLastError());
3110 if (GetLastError() == ERROR_ACCESS_DENIED)
3111 *_errno() = EBADF;
3112 return -1;
3116 if (count > 4)
3117 TRACE("(%lu), %s\n", num_read, debugstr_an(buf, num_read));
3118 return num_read;
3121 /*********************************************************************
3122 * _read (MSVCRT.@)
3124 int CDECL _read(int fd, void *buf, unsigned int count)
3126 ioinfo *info;
3127 int num_read;
3129 if(fd == MSVCRT_NO_CONSOLE_FD) {
3130 *_errno() = EBADF;
3131 return -1;
3134 info = get_ioinfo(fd);
3135 num_read = read_i(fd, info, buf, count);
3136 release_ioinfo(info);
3137 return num_read;
3140 /*********************************************************************
3141 * _setmode (MSVCRT.@)
3143 int CDECL _setmode(int fd,int mode)
3145 ioinfo *info = get_ioinfo(fd);
3146 int ret = info->wxflag & WX_TEXT ? _O_TEXT : _O_BINARY;
3148 if(ret==_O_TEXT && ioinfo_get_textmode(info) != TEXTMODE_ANSI)
3149 ret = _O_WTEXT;
3151 if(mode!=_O_TEXT && mode!=_O_BINARY && mode!=_O_WTEXT
3152 && mode!=_O_U16TEXT && mode!=_O_U8TEXT) {
3153 *_errno() = EINVAL;
3154 release_ioinfo(info);
3155 return -1;
3158 if(info == &MSVCRT___badioinfo) {
3159 *_errno() = EBADF;
3160 return EOF;
3163 if(mode == _O_BINARY) {
3164 info->wxflag &= ~WX_TEXT;
3165 ioinfo_set_textmode(info, TEXTMODE_ANSI);
3166 release_ioinfo(info);
3167 return ret;
3170 info->wxflag |= WX_TEXT;
3171 if(mode == _O_TEXT)
3172 ioinfo_set_textmode(info, TEXTMODE_ANSI);
3173 else if(mode == _O_U8TEXT)
3174 ioinfo_set_textmode(info, TEXTMODE_UTF8);
3175 else
3176 ioinfo_set_textmode(info, TEXTMODE_UTF16LE);
3178 release_ioinfo(info);
3179 return ret;
3182 /*********************************************************************
3183 * _stat64 (MSVCRT.@)
3185 int CDECL _stat64(const char* path, struct _stat64 * buf)
3187 DWORD dw;
3188 WIN32_FILE_ATTRIBUTE_DATA hfi;
3189 unsigned short mode = ALL_S_IREAD;
3190 int plen;
3192 TRACE(":file (%s) buf(%p)\n", path, buf);
3194 plen = strlen(path);
3195 while (plen && path[plen-1]==' ')
3196 plen--;
3198 if (plen==2 && path[1]==':')
3200 *_errno() = ENOENT;
3201 return -1;
3204 #if _MSVCR_VER<140
3205 if (plen>=2 && path[plen-2]!=':' && (path[plen-1]=='\\' || path[plen-1]=='/'))
3207 *_errno() = ENOENT;
3208 return -1;
3210 #endif
3212 if (!GetFileAttributesExA(path, GetFileExInfoStandard, &hfi))
3214 TRACE("failed (%ld)\n", GetLastError());
3215 *_errno() = ENOENT;
3216 return -1;
3219 memset(buf,0,sizeof(struct _stat64));
3221 /* FIXME: rdev isn't drive num, despite what the docs say-what is it?
3222 Bon 011120: This FIXME seems incorrect
3223 Also a letter as first char isn't enough to be classified
3224 as a drive letter
3226 if (isalpha(*path)&& (*(path+1)==':'))
3227 buf->st_dev = buf->st_rdev = _toupper_l(*path, NULL) - 'A'; /* drive num */
3228 else
3229 buf->st_dev = buf->st_rdev = _getdrive() - 1;
3231 /* Dir, or regular file? */
3232 if (hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3233 mode |= (_S_IFDIR | ALL_S_IEXEC);
3234 else
3236 mode |= _S_IFREG;
3237 /* executable? */
3238 if (plen > 6 && path[plen-4] == '.') /* shortest exe: "\x.exe" */
3240 unsigned int ext = _tolower_l(path[plen-1], NULL) |
3241 (_tolower_l(path[plen-2], NULL) << 8) |
3242 (_tolower_l(path[plen-3], NULL) << 16);
3243 if (ext == EXE || ext == BAT || ext == CMD || ext == COM)
3244 mode |= ALL_S_IEXEC;
3248 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
3249 mode |= ALL_S_IWRITE;
3251 buf->st_mode = mode;
3252 buf->st_nlink = 1;
3253 buf->st_size = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
3254 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
3255 buf->st_atime = dw;
3256 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
3257 buf->st_mtime = buf->st_ctime = dw;
3258 TRACE("%d %d %#I64x %I64d %I64d %I64d\n", buf->st_mode, buf->st_nlink,
3259 buf->st_size, buf->st_atime, buf->st_mtime, buf->st_ctime);
3260 return 0;
3263 /*********************************************************************
3264 * _stati64 (MSVCRT.@)
3266 int CDECL _stati64(const char* path, struct _stati64 * buf)
3268 int ret;
3269 struct _stat64 buf64;
3271 ret = _stat64(path, &buf64);
3272 if (!ret)
3273 msvcrt_stat64_to_stati64(&buf64, buf);
3274 return ret;
3277 /*********************************************************************
3278 * _stat (MSVCRT.@)
3280 int CDECL _stat(const char* path, struct _stat * buf)
3282 int ret;
3283 struct _stat64 buf64;
3285 ret = _stat64( path, &buf64);
3286 if (!ret)
3287 msvcrt_stat64_to_stat(&buf64, buf);
3288 return ret;
3291 #if _MSVCR_VER >= 80
3293 /*********************************************************************
3294 * _stat32 (MSVCR80.@)
3296 int CDECL _stat32(const char *path, struct _stat32 *buf)
3298 int ret;
3299 struct _stat64 buf64;
3301 ret = _stat64(path, &buf64);
3302 if (!ret)
3303 msvcrt_stat64_to_stat32(&buf64, buf);
3304 return ret;
3307 /*********************************************************************
3308 * _stat32i64 (MSVCR80.@)
3310 int CDECL _stat32i64(const char *path, struct _stat32i64 *buf)
3312 int ret;
3313 struct _stat64 buf64;
3315 ret = _stat64(path, &buf64);
3316 if (!ret)
3317 msvcrt_stat64_to_stat32i64(&buf64, buf);
3318 return ret;
3321 /*********************************************************************
3322 * _stat64i32 (MSVCR80.@)
3324 int CDECL _stat64i32(const char* path, struct _stat64i32 *buf)
3326 int ret;
3327 struct _stat64 buf64;
3329 ret = _stat64(path, &buf64);
3330 if (!ret)
3331 msvcrt_stat64_to_stat64i32(&buf64, buf);
3332 return ret;
3335 #endif /* _MSVCR_VER >= 80 */
3337 /*********************************************************************
3338 * _wstat64 (MSVCRT.@)
3340 int CDECL _wstat64(const wchar_t* path, struct _stat64 * buf)
3342 DWORD dw;
3343 WIN32_FILE_ATTRIBUTE_DATA hfi;
3344 unsigned short mode = ALL_S_IREAD;
3345 int plen;
3347 TRACE(":file (%s) buf(%p)\n", debugstr_w(path), buf);
3349 plen = wcslen(path);
3350 while (plen && path[plen-1]==' ')
3351 plen--;
3353 if (plen==2 && path[1]==':')
3355 *_errno() = ENOENT;
3356 return -1;
3359 #if _MSVCR_VER<140
3360 if (plen>=2 && path[plen-2]!=':' && (path[plen-1]=='\\' || path[plen-1]=='/'))
3362 *_errno() = ENOENT;
3363 return -1;
3365 #endif
3367 if (!GetFileAttributesExW(path, GetFileExInfoStandard, &hfi))
3369 TRACE("failed (%ld)\n", GetLastError());
3370 *_errno() = ENOENT;
3371 return -1;
3374 memset(buf,0,sizeof(struct _stat64));
3376 /* FIXME: rdev isn't drive num, despite what the docs says-what is it? */
3377 if (iswalpha(*path) && path[1] == ':')
3378 buf->st_dev = buf->st_rdev = towupper(*path) - 'A'; /* drive num */
3379 else
3380 buf->st_dev = buf->st_rdev = _getdrive() - 1;
3382 /* Dir, or regular file? */
3383 if (hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
3384 mode |= (_S_IFDIR | ALL_S_IEXEC);
3385 else
3387 mode |= _S_IFREG;
3388 /* executable? */
3389 if (plen > 6 && path[plen-4] == '.') /* shortest exe: "\x.exe" */
3391 ULONGLONG ext = towlower(path[plen-1]) | (towlower(path[plen-2]) << 16) |
3392 ((ULONGLONG)towlower(path[plen-3]) << 32);
3393 if (ext == WCEXE || ext == WCBAT || ext == WCCMD || ext == WCCOM)
3394 mode |= ALL_S_IEXEC;
3398 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
3399 mode |= ALL_S_IWRITE;
3401 buf->st_mode = mode;
3402 buf->st_nlink = 1;
3403 buf->st_size = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
3404 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
3405 buf->st_atime = dw;
3406 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
3407 buf->st_mtime = buf->st_ctime = dw;
3408 TRACE("%d %d %#I64x %I64d %I64d %I64d\n", buf->st_mode, buf->st_nlink,
3409 buf->st_size, buf->st_atime, buf->st_mtime, buf->st_ctime);
3410 return 0;
3413 /*********************************************************************
3414 * _wstati64 (MSVCRT.@)
3416 int CDECL _wstati64(const wchar_t* path, struct _stati64 * buf)
3418 int ret;
3419 struct _stat64 buf64;
3421 ret = _wstat64(path, &buf64);
3422 if (!ret)
3423 msvcrt_stat64_to_stati64(&buf64, buf);
3424 return ret;
3427 /*********************************************************************
3428 * _wstat (MSVCRT.@)
3430 int CDECL _wstat(const wchar_t* path, struct _stat * buf)
3432 int ret;
3433 struct _stat64 buf64;
3435 ret = _wstat64( path, &buf64 );
3436 if (!ret) msvcrt_stat64_to_stat(&buf64, buf);
3437 return ret;
3440 #if _MSVCR_VER >= 80
3442 /*********************************************************************
3443 * _wstat32 (MSVCR80.@)
3445 int CDECL _wstat32(const wchar_t *path, struct _stat32 *buf)
3447 int ret;
3448 struct _stat64 buf64;
3450 ret = _wstat64(path, &buf64);
3451 if (!ret)
3452 msvcrt_stat64_to_stat32(&buf64, buf);
3453 return ret;
3456 /*********************************************************************
3457 * _wstat32i64 (MSVCR80.@)
3459 int CDECL _wstat32i64(const wchar_t *path, struct _stat32i64 *buf)
3461 int ret;
3462 struct _stat64 buf64;
3464 ret = _wstat64(path, &buf64);
3465 if (!ret)
3466 msvcrt_stat64_to_stat32i64(&buf64, buf);
3467 return ret;
3470 /*********************************************************************
3471 * _wstat64i32 (MSVCR80.@)
3473 int CDECL _wstat64i32(const wchar_t *path, struct _stat64i32 *buf)
3475 int ret;
3476 struct _stat64 buf64;
3478 ret = _wstat64(path, &buf64);
3479 if (!ret)
3480 msvcrt_stat64_to_stat64i32(&buf64, buf);
3481 return ret;
3484 #endif /* _MSVCR_VER >= 80 */
3486 /*********************************************************************
3487 * _tell (MSVCRT.@)
3489 __msvcrt_long CDECL _tell(int fd)
3491 return _lseek(fd, 0, SEEK_CUR);
3494 /*********************************************************************
3495 * _telli64 (MSVCRT.@)
3497 __int64 CDECL _telli64(int fd)
3499 return _lseeki64(fd, 0, SEEK_CUR);
3502 /*********************************************************************
3503 * _tempnam (MSVCRT.@)
3505 char * CDECL _tempnam(const char *dir, const char *prefix)
3507 char tmpbuf[MAX_PATH];
3508 const char *tmp_dir = getenv("TMP");
3510 if (tmp_dir) dir = tmp_dir;
3512 TRACE("dir (%s) prefix (%s)\n", dir, prefix);
3513 if (GetTempFileNameA(dir,prefix,0,tmpbuf))
3515 TRACE("got name (%s)\n", tmpbuf);
3516 DeleteFileA(tmpbuf);
3517 return _strdup(tmpbuf);
3519 TRACE("failed (%ld)\n", GetLastError());
3520 return NULL;
3523 /*********************************************************************
3524 * _wtempnam (MSVCRT.@)
3526 wchar_t * CDECL _wtempnam(const wchar_t *dir, const wchar_t *prefix)
3528 wchar_t tmpbuf[MAX_PATH];
3529 const wchar_t *tmp_dir = _wgetenv(L"TMP");
3531 if (tmp_dir) dir = tmp_dir;
3533 TRACE("dir (%s) prefix (%s)\n", debugstr_w(dir), debugstr_w(prefix));
3534 if (GetTempFileNameW(dir,prefix,0,tmpbuf))
3536 TRACE("got name (%s)\n", debugstr_w(tmpbuf));
3537 DeleteFileW(tmpbuf);
3538 return _wcsdup(tmpbuf);
3540 TRACE("failed (%ld)\n", GetLastError());
3541 return NULL;
3544 /*********************************************************************
3545 * _umask (MSVCRT.@)
3547 int CDECL _umask(int umask)
3549 int old_umask = MSVCRT_umask;
3550 TRACE("(%d)\n",umask);
3551 MSVCRT_umask = umask;
3552 return old_umask;
3555 /*********************************************************************
3556 * _utime64 (MSVCRT.@)
3558 int CDECL _utime64(const char* path, struct __utimbuf64 *t)
3560 int fd = _open(path, _O_WRONLY | _O_BINARY);
3562 if (fd > 0)
3564 int retVal = _futime64(fd, t);
3565 _close(fd);
3566 return retVal;
3568 return -1;
3571 /*********************************************************************
3572 * _utime32 (MSVCRT.@)
3574 int CDECL _utime32(const char* path, struct __utimbuf32 *t)
3576 if (t)
3578 struct __utimbuf64 t64;
3579 t64.actime = t->actime;
3580 t64.modtime = t->modtime;
3581 return _utime64( path, &t64 );
3583 else
3584 return _utime64( path, NULL );
3587 /*********************************************************************
3588 * _wutime64 (MSVCRT.@)
3590 int CDECL _wutime64(const wchar_t* path, struct __utimbuf64 *t)
3592 int fd = _wopen(path, _O_WRONLY | _O_BINARY);
3594 if (fd > 0)
3596 int retVal = _futime64(fd, t);
3597 _close(fd);
3598 return retVal;
3600 return -1;
3603 /*********************************************************************
3604 * _wutime32 (MSVCRT.@)
3606 int CDECL _wutime32(const wchar_t* path, struct __utimbuf32 *t)
3608 if (t)
3610 struct __utimbuf64 t64;
3611 t64.actime = t->actime;
3612 t64.modtime = t->modtime;
3613 return _wutime64( path, &t64 );
3615 else
3616 return _wutime64( path, NULL );
3619 /*********************************************************************
3620 * _write (MSVCRT.@)
3622 int CDECL _write(int fd, const void* buf, unsigned int count)
3624 ioinfo *info = get_ioinfo(fd);
3625 HANDLE hand = info->handle;
3626 DWORD num_written, i;
3627 BOOL console = FALSE;
3629 if (hand == INVALID_HANDLE_VALUE || fd == MSVCRT_NO_CONSOLE_FD)
3631 *_errno() = EBADF;
3632 release_ioinfo(info);
3633 return -1;
3636 if (ioinfo_get_textmode(info) != TEXTMODE_ANSI && count&1)
3638 *_errno() = EINVAL;
3639 release_ioinfo(info);
3640 return -1;
3643 /* If appending, go to EOF */
3644 if (info->wxflag & WX_APPEND)
3645 _lseek(fd, 0, FILE_END);
3647 if (!(info->wxflag & WX_TEXT))
3649 if (!WriteFile(hand, buf, count, &num_written, NULL)
3650 || num_written != count)
3652 TRACE("WriteFile (fd %d, hand %p) failed-last error (%ld)\n", fd,
3653 hand, GetLastError());
3654 msvcrt_set_errno(GetLastError());
3655 if (GetLastError() == ERROR_ACCESS_DENIED)
3656 *_errno() = EBADF;
3657 num_written = -1;
3660 release_ioinfo(info);
3661 return num_written;
3664 if (_isatty(fd)) console = VerifyConsoleIoHandle(hand);
3665 for (i = 0; i < count;)
3667 const char *s = buf;
3668 char lfbuf[2048];
3669 DWORD j = 0;
3671 if (ioinfo_get_textmode(info) == TEXTMODE_ANSI && console)
3673 char conv[sizeof(lfbuf)];
3674 size_t len = 0;
3676 #if _MSVCR_VER >= 80
3677 if (info->dbcsBufferUsed)
3679 conv[j++] = info->dbcsBuffer[0];
3680 info->dbcsBufferUsed = FALSE;
3681 conv[j++] = s[i++];
3682 len++;
3684 #endif
3686 for (; i < count && j < sizeof(conv)-1 &&
3687 len < (sizeof(lfbuf) - 1) / sizeof(WCHAR); i++, j++, len++)
3689 if (isleadbyte((unsigned char)s[i]))
3691 conv[j++] = s[i++];
3693 if (i == count)
3695 #if _MSVCR_VER >= 80
3696 info->dbcsBuffer[0] = conv[j-1];
3697 info->dbcsBufferUsed = TRUE;
3698 break;
3699 #else
3700 *_errno() = EINVAL;
3701 release_ioinfo(info);
3702 return -1;
3703 #endif
3706 else if (s[i] == '\n')
3708 conv[j++] = '\r';
3709 len++;
3711 conv[j] = s[i];
3714 len = mbstowcs((WCHAR*)lfbuf, conv, len);
3715 if (len == -1)
3717 msvcrt_set_errno(GetLastError());
3718 release_ioinfo(info);
3719 return -1;
3721 j = len * 2;
3723 else if (ioinfo_get_textmode(info) == TEXTMODE_ANSI)
3725 for (j = 0; i < count && j < sizeof(lfbuf)-1; i++, j++)
3727 if (s[i] == '\n')
3728 lfbuf[j++] = '\r';
3729 lfbuf[j] = s[i];
3732 else if (ioinfo_get_textmode(info) == TEXTMODE_UTF16LE || console)
3734 for (j = 0; i < count && j < sizeof(lfbuf)-3; i++, j++)
3736 if (s[i] == '\n' && !s[i+1])
3738 lfbuf[j++] = '\r';
3739 lfbuf[j++] = 0;
3741 lfbuf[j++] = s[i++];
3742 lfbuf[j] = s[i];
3745 else
3747 char conv[sizeof(lfbuf)/4];
3749 for (j = 0; i < count && j < sizeof(conv)-3; i++, j++)
3751 if (s[i] == '\n' && !s[i+1])
3753 conv[j++] = '\r';
3754 conv[j++] = 0;
3756 conv[j++] = s[i++];
3757 conv[j] = s[i];
3760 j = WideCharToMultiByte(CP_UTF8, 0, (WCHAR*)conv, j/2, lfbuf, sizeof(lfbuf), NULL, NULL);
3761 if (!j)
3763 msvcrt_set_errno(GetLastError());
3764 release_ioinfo(info);
3765 return -1;
3769 if (console)
3771 j = j/2;
3772 if (!WriteConsoleW(hand, lfbuf, j, &num_written, NULL))
3773 num_written = -1;
3775 else if (!WriteFile(hand, lfbuf, j, &num_written, NULL))
3777 num_written = -1;
3780 if (num_written != j)
3782 TRACE("WriteFile/WriteConsoleW (fd %d, hand %p) failed-last error (%ld)\n", fd,
3783 hand, GetLastError());
3784 msvcrt_set_errno(GetLastError());
3785 if (GetLastError() == ERROR_ACCESS_DENIED)
3786 *_errno() = EBADF;
3787 release_ioinfo(info);
3788 return -1;
3792 release_ioinfo(info);
3793 return count;
3796 /*********************************************************************
3797 * _putw (MSVCRT.@)
3799 int CDECL _putw(int val, FILE* file)
3801 int len;
3803 _lock_file(file);
3804 len = _write(file->_file, &val, sizeof(val));
3805 if (len == sizeof(val)) {
3806 _unlock_file(file);
3807 return val;
3810 file->_flag |= _IOERR;
3811 _unlock_file(file);
3812 return EOF;
3815 /*********************************************************************
3816 * fclose (MSVCRT.@)
3818 int CDECL fclose(FILE* file)
3820 int ret;
3822 if (!MSVCRT_CHECK_PMT(file != NULL)) return EOF;
3824 _lock_file(file);
3825 ret = _fclose_nolock(file);
3826 _unlock_file(file);
3828 return ret;
3831 /*********************************************************************
3832 * _fclose_nolock (MSVCRT.@)
3834 int CDECL _fclose_nolock(FILE* file)
3836 int r, flag;
3838 if (!MSVCRT_CHECK_PMT(file != NULL)) return EOF;
3840 if(!(file->_flag & (_IOREAD | _IOWRT | _IORW)))
3842 file->_flag = 0;
3843 return EOF;
3846 flag = file->_flag;
3847 free(file->_tmpfname);
3848 file->_tmpfname = NULL;
3849 /* flush stdio buffers */
3850 if(file->_flag & _IOWRT)
3851 _fflush_nolock(file);
3852 if(file->_flag & _IOMYBUF)
3853 free(file->_base);
3855 r=_close(file->_file);
3856 file->_flag = 0;
3858 return ((r == -1) || (flag & _IOERR) ? EOF : 0);
3861 /*********************************************************************
3862 * feof (MSVCRT.@)
3864 int CDECL feof(FILE* file)
3866 return file->_flag & _IOEOF;
3869 /*********************************************************************
3870 * ferror (MSVCRT.@)
3872 int CDECL ferror(FILE* file)
3874 return file->_flag & _IOERR;
3877 /*********************************************************************
3878 * _filbuf (MSVCRT.@)
3880 int CDECL _filbuf(FILE* file)
3882 unsigned char c;
3884 if(file->_flag & _IOSTRG)
3885 return EOF;
3887 /* Allocate buffer if needed */
3888 if(!(file->_flag & (MSVCRT__NOBUF | _IOMYBUF | MSVCRT__USERBUF)))
3889 msvcrt_alloc_buffer(file);
3891 if(!(file->_flag & _IOREAD)) {
3892 if(file->_flag & _IORW)
3893 file->_flag |= _IOREAD;
3894 else
3895 return EOF;
3898 if(!(file->_flag & (_IOMYBUF | MSVCRT__USERBUF))) {
3899 int r;
3900 if ((r = _read(file->_file,&c,1)) != 1) {
3901 file->_flag |= (r == 0) ? _IOEOF : _IOERR;
3902 return EOF;
3905 return c;
3906 } else {
3907 file->_cnt = _read(file->_file, file->_base, file->_bufsiz);
3908 if(file->_cnt<=0) {
3909 file->_flag |= (file->_cnt == 0) ? _IOEOF : _IOERR;
3910 file->_cnt = 0;
3911 return EOF;
3914 file->_cnt--;
3915 file->_ptr = file->_base+1;
3916 c = *(unsigned char *)file->_base;
3917 return c;
3921 /*********************************************************************
3922 * fgetc (MSVCRT.@)
3924 int CDECL fgetc(FILE* file)
3926 int ret;
3928 _lock_file(file);
3929 ret = _fgetc_nolock(file);
3930 _unlock_file(file);
3932 return ret;
3935 /*********************************************************************
3936 * _fgetc_nolock (MSVCRT.@)
3938 int CDECL _fgetc_nolock(FILE* file)
3940 unsigned char *i;
3941 unsigned int j;
3943 if (file->_cnt>0) {
3944 file->_cnt--;
3945 i = (unsigned char *)file->_ptr++;
3946 j = *i;
3947 } else
3948 j = _filbuf(file);
3950 return j;
3953 /*********************************************************************
3954 * _fgetchar (MSVCRT.@)
3956 int CDECL _fgetchar(void)
3958 return fgetc(stdin);
3961 /*********************************************************************
3962 * fgets (MSVCRT.@)
3964 char * CDECL fgets(char *s, int size, FILE* file)
3966 int cc = EOF;
3967 char * buf_start = s;
3969 TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
3970 file,file->_file,s,size);
3972 _lock_file(file);
3974 while ((size >1) && (cc = _fgetc_nolock(file)) != EOF && cc != '\n')
3976 *s++ = (char)cc;
3977 size --;
3979 if ((cc == EOF) && (s == buf_start)) /* If nothing read, return 0*/
3981 TRACE(":nothing read\n");
3982 _unlock_file(file);
3983 return NULL;
3985 if ((cc != EOF) && (size > 1))
3986 *s++ = cc;
3987 *s = '\0';
3988 TRACE(":got %s\n", debugstr_a(buf_start));
3989 _unlock_file(file);
3990 return buf_start;
3993 /*********************************************************************
3994 * fgetwc (MSVCRT.@)
3996 wint_t CDECL fgetwc(FILE* file)
3998 wint_t ret;
4000 _lock_file(file);
4001 ret = _fgetwc_nolock(file);
4002 _unlock_file(file);
4004 return ret;
4007 /*********************************************************************
4008 * _fgetwc_nolock (MSVCRT.@)
4010 wint_t CDECL _fgetwc_nolock(FILE* file)
4012 wint_t ret;
4013 int ch;
4015 if(ioinfo_get_textmode(get_ioinfo_nolock(file->_file)) != TEXTMODE_ANSI
4016 || !(get_ioinfo_nolock(file->_file)->wxflag & WX_TEXT)) {
4017 char *p;
4019 for(p=(char*)&ret; (wint_t*)p<&ret+1; p++) {
4020 ch = _fgetc_nolock(file);
4021 if(ch == EOF) {
4022 ret = WEOF;
4023 break;
4025 *p = (char)ch;
4027 }else {
4028 char mbs[MB_LEN_MAX];
4029 int len = 0;
4031 ch = _fgetc_nolock(file);
4032 if(ch != EOF) {
4033 mbs[0] = (char)ch;
4034 if(isleadbyte((unsigned char)mbs[0])) {
4035 ch = _fgetc_nolock(file);
4036 if(ch != EOF) {
4037 mbs[1] = (char)ch;
4038 len = 2;
4040 }else {
4041 len = 1;
4045 if(!len || mbtowc(&ret, mbs, len)==-1)
4046 ret = WEOF;
4049 return ret;
4052 /*********************************************************************
4053 * _getw (MSVCRT.@)
4055 int CDECL _getw(FILE* file)
4057 char *ch;
4058 int i, k;
4059 unsigned int j;
4060 ch = (char *)&i;
4062 _lock_file(file);
4063 for (j=0; j<sizeof(int); j++) {
4064 k = _fgetc_nolock(file);
4065 if (k == EOF) {
4066 file->_flag |= _IOEOF;
4067 _unlock_file(file);
4068 return EOF;
4070 ch[j] = k;
4073 _unlock_file(file);
4074 return i;
4077 /*********************************************************************
4078 * getwc (MSVCRT.@)
4080 wint_t CDECL getwc(FILE* file)
4082 return fgetwc(file);
4085 /*********************************************************************
4086 * _fgetwchar (MSVCRT.@)
4088 wint_t CDECL _fgetwchar(void)
4090 return fgetwc(stdin);
4093 /*********************************************************************
4094 * getwchar (MSVCRT.@)
4096 wint_t CDECL getwchar(void)
4098 return _fgetwchar();
4101 /*********************************************************************
4102 * fgetws (MSVCRT.@)
4104 wchar_t * CDECL fgetws(wchar_t *s, int size, FILE* file)
4106 wint_t cc = WEOF;
4107 wchar_t * buf_start = s;
4109 TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
4110 file,file->_file,s,size);
4112 _lock_file(file);
4114 while ((size >1) && (cc = _fgetwc_nolock(file)) != WEOF && cc != '\n')
4116 *s++ = cc;
4117 size --;
4119 if ((cc == WEOF) && (s == buf_start)) /* If nothing read, return 0*/
4121 TRACE(":nothing read\n");
4122 _unlock_file(file);
4123 return NULL;
4125 if ((cc != WEOF) && (size > 1))
4126 *s++ = cc;
4127 *s = 0;
4128 TRACE(":got %s\n", debugstr_w(buf_start));
4129 _unlock_file(file);
4130 return buf_start;
4133 /*********************************************************************
4134 * _flsbuf (MSVCRT.@)
4136 int CDECL _flsbuf(int c, FILE* file)
4138 /* Flush output buffer */
4139 if(!(file->_flag & (MSVCRT__NOBUF | _IOMYBUF | MSVCRT__USERBUF))) {
4140 msvcrt_alloc_buffer(file);
4143 if(!(file->_flag & _IOWRT)) {
4144 if(!(file->_flag & _IORW)) {
4145 file->_flag |= _IOERR;
4146 *_errno() = EBADF;
4147 return EOF;
4149 file->_flag |= _IOWRT;
4151 if(file->_flag & _IOREAD) {
4152 if(!(file->_flag & _IOEOF)) {
4153 file->_flag |= _IOERR;
4154 return EOF;
4156 file->_cnt = 0;
4157 file->_ptr = file->_base;
4158 file->_flag &= ~(_IOREAD | _IOEOF);
4161 if(file->_flag & (_IOMYBUF | MSVCRT__USERBUF)) {
4162 int res = 0;
4164 if(file->_cnt <= 0) {
4165 res = msvcrt_flush_buffer(file);
4166 if(res)
4167 return res;
4168 file->_flag |= _IOWRT;
4169 file->_cnt=file->_bufsiz;
4171 *file->_ptr++ = c;
4172 file->_cnt--;
4173 return c&0xff;
4174 } else {
4175 unsigned char cc=c;
4176 int len;
4177 /* set _cnt to 0 for unbuffered FILEs */
4178 file->_cnt = 0;
4179 len = _write(file->_file, &cc, 1);
4180 if (len == 1)
4181 return c & 0xff;
4182 file->_flag |= _IOERR;
4183 return EOF;
4187 /*********************************************************************
4188 * fwrite (MSVCRT.@)
4190 size_t CDECL fwrite(const void *ptr, size_t size, size_t nmemb, FILE* file)
4192 size_t ret;
4194 _lock_file(file);
4195 ret = _fwrite_nolock(ptr, size, nmemb, file);
4196 _unlock_file(file);
4198 return ret;
4201 /*********************************************************************
4202 * _fwrite_nolock (MSVCRT.@)
4204 size_t CDECL _fwrite_nolock(const void *ptr, size_t size, size_t nmemb, FILE* file)
4206 size_t wrcnt=size * nmemb;
4207 int written = 0;
4208 if (size == 0)
4209 return 0;
4211 while(wrcnt) {
4212 if(file->_cnt < 0) {
4213 WARN("negative file->_cnt value in %p\n", file);
4214 file->_flag |= _IOERR;
4215 break;
4216 } else if(file->_cnt) {
4217 int pcnt=(file->_cnt>wrcnt)? wrcnt: file->_cnt;
4218 memcpy(file->_ptr, ptr, pcnt);
4219 file->_cnt -= pcnt;
4220 file->_ptr += pcnt;
4221 written += pcnt;
4222 wrcnt -= pcnt;
4223 ptr = (const char*)ptr + pcnt;
4224 } else if((file->_flag & MSVCRT__NOBUF)
4225 || ((file->_flag & (_IOMYBUF | MSVCRT__USERBUF)) && wrcnt >= file->_bufsiz)
4226 || (!(file->_flag & (_IOMYBUF | MSVCRT__USERBUF)) && wrcnt >= MSVCRT_INTERNAL_BUFSIZ)) {
4227 size_t pcnt;
4228 int bufsiz;
4230 if(file->_flag & MSVCRT__NOBUF)
4231 bufsiz = 1;
4232 else if(!(file->_flag & (_IOMYBUF | MSVCRT__USERBUF)))
4233 bufsiz = MSVCRT_INTERNAL_BUFSIZ;
4234 else
4235 bufsiz = file->_bufsiz;
4237 pcnt = (wrcnt / bufsiz) * bufsiz;
4239 if(msvcrt_flush_buffer(file) == EOF)
4240 break;
4242 if(_write(file->_file, ptr, pcnt) <= 0) {
4243 file->_flag |= _IOERR;
4244 break;
4246 written += pcnt;
4247 wrcnt -= pcnt;
4248 ptr = (const char*)ptr + pcnt;
4249 } else {
4250 if(_flsbuf(*(const char*)ptr, file) == EOF)
4251 break;
4252 written++;
4253 wrcnt--;
4254 ptr = (const char*)ptr + 1;
4258 return written / size;
4261 /*********************************************************************
4262 * fputwc (MSVCRT.@)
4264 wint_t CDECL fputwc(wint_t wc, FILE* file)
4266 wint_t ret;
4268 _lock_file(file);
4269 ret = _fputwc_nolock(wc, file);
4270 _unlock_file(file);
4272 return ret;
4275 /*********************************************************************
4276 * _fputwc_nolock (MSVCRT.@)
4278 wint_t CDECL _fputwc_nolock(wint_t wc, FILE* file)
4280 wchar_t mwc=wc;
4281 ioinfo *fdinfo;
4282 wint_t ret;
4284 fdinfo = get_ioinfo_nolock(file->_file);
4286 if((fdinfo->wxflag&WX_TEXT) && ioinfo_get_textmode(fdinfo) == TEXTMODE_ANSI) {
4287 char buf[MB_LEN_MAX];
4288 int char_len;
4290 char_len = wctomb(buf, mwc);
4291 if(char_len!=-1 && _fwrite_nolock(buf, char_len, 1, file)==1)
4292 ret = wc;
4293 else
4294 ret = WEOF;
4295 }else if(_fwrite_nolock(&mwc, sizeof(mwc), 1, file) == 1) {
4296 ret = wc;
4297 }else {
4298 ret = WEOF;
4301 return ret;
4304 /*********************************************************************
4305 * _fputwchar (MSVCRT.@)
4307 wint_t CDECL _fputwchar(wint_t wc)
4309 return fputwc(wc, stdout);
4312 /*********************************************************************
4313 * _wfsopen (MSVCRT.@)
4315 FILE * CDECL _wfsopen(const wchar_t *path, const wchar_t *mode, int share)
4317 FILE* file;
4318 int open_flags, stream_flags, fd;
4320 TRACE("(%s,%s)\n", debugstr_w(path), debugstr_w(mode));
4322 /* map mode string to open() flags. "man fopen" for possibilities. */
4323 if (msvcrt_get_flags(mode, &open_flags, &stream_flags) == -1)
4324 return NULL;
4326 LOCK_FILES();
4327 fd = _wsopen(path, open_flags, share, _S_IREAD | _S_IWRITE);
4328 if (fd < 0)
4329 file = NULL;
4330 else if ((file = msvcrt_alloc_fp()) && msvcrt_init_fp(file, fd, stream_flags)
4331 != -1)
4332 TRACE(":fd (%d) mode (%s) FILE* (%p)\n", fd, debugstr_w(mode), file);
4333 else if (file)
4335 file->_flag = 0;
4336 file = NULL;
4339 TRACE(":got (%p)\n",file);
4340 if (fd >= 0 && !file)
4341 _close(fd);
4342 UNLOCK_FILES();
4343 return file;
4346 /*********************************************************************
4347 * _fsopen (MSVCRT.@)
4349 FILE * CDECL _fsopen(const char *path, const char *mode, int share)
4351 FILE *ret;
4352 wchar_t *pathW = NULL, *modeW = NULL;
4354 if (path && !(pathW = msvcrt_wstrdupa(path))) {
4355 _invalid_parameter(NULL, NULL, NULL, 0, 0);
4356 *_errno() = EINVAL;
4357 return NULL;
4359 if (mode && !(modeW = msvcrt_wstrdupa(mode)))
4361 free(pathW);
4362 _invalid_parameter(NULL, NULL, NULL, 0, 0);
4363 *_errno() = EINVAL;
4364 return NULL;
4367 ret = _wfsopen(pathW, modeW, share);
4369 free(pathW);
4370 free(modeW);
4371 return ret;
4374 /*********************************************************************
4375 * fopen (MSVCRT.@)
4377 FILE * CDECL fopen(const char *path, const char *mode)
4379 return _fsopen( path, mode, _SH_DENYNO );
4382 /*********************************************************************
4383 * fopen_s (MSVCRT.@)
4385 int CDECL fopen_s(FILE** pFile,
4386 const char *filename, const char *mode)
4388 if (!MSVCRT_CHECK_PMT(pFile != NULL)) return EINVAL;
4389 if (!MSVCRT_CHECK_PMT(filename != NULL)) return EINVAL;
4390 if (!MSVCRT_CHECK_PMT(mode != NULL)) return EINVAL;
4392 *pFile = fopen(filename, mode);
4394 if(!*pFile)
4395 return *_errno();
4396 return 0;
4399 /*********************************************************************
4400 * _wfopen (MSVCRT.@)
4402 FILE * CDECL _wfopen(const wchar_t *path, const wchar_t *mode)
4404 return _wfsopen( path, mode, _SH_DENYNO );
4407 /*********************************************************************
4408 * _wfopen_s (MSVCRT.@)
4410 int CDECL _wfopen_s(FILE** pFile, const wchar_t *filename,
4411 const wchar_t *mode)
4413 if (!MSVCRT_CHECK_PMT(pFile != NULL)) return EINVAL;
4414 if (!MSVCRT_CHECK_PMT(filename != NULL)) return EINVAL;
4415 if (!MSVCRT_CHECK_PMT(mode != NULL)) return EINVAL;
4417 *pFile = _wfopen(filename, mode);
4419 if(!*pFile)
4420 return *_errno();
4421 return 0;
4424 /*********************************************************************
4425 * fputc (MSVCRT.@)
4427 int CDECL fputc(int c, FILE* file)
4429 int ret;
4431 _lock_file(file);
4432 ret = _fputc_nolock(c, file);
4433 _unlock_file(file);
4435 return ret;
4438 /*********************************************************************
4439 * _fputc_nolock (MSVCRT.@)
4441 int CDECL _fputc_nolock(int c, FILE* file)
4443 int res;
4445 if(file->_cnt>0) {
4446 *file->_ptr++=c;
4447 file->_cnt--;
4448 if (c == '\n')
4450 res = msvcrt_flush_buffer(file);
4451 return res ? res : c;
4453 else {
4454 return c & 0xff;
4456 } else {
4457 res = _flsbuf(c, file);
4458 return res;
4462 /*********************************************************************
4463 * _fputchar (MSVCRT.@)
4465 int CDECL _fputchar(int c)
4467 return fputc(c, stdout);
4470 /*********************************************************************
4471 * fread (MSVCRT.@)
4473 size_t CDECL fread(void *ptr, size_t size, size_t nmemb, FILE* file)
4475 size_t ret;
4477 _lock_file(file);
4478 ret = _fread_nolock(ptr, size, nmemb, file);
4479 _unlock_file(file);
4481 return ret;
4484 /*********************************************************************
4485 * _fread_nolock (MSVCRT.@)
4487 size_t CDECL _fread_nolock(void *ptr, size_t size, size_t nmemb, FILE* file)
4489 size_t rcnt=size * nmemb;
4490 size_t read=0;
4491 size_t pread=0;
4493 if(!rcnt)
4494 return 0;
4496 /* first buffered data */
4497 if(file->_cnt>0) {
4498 int pcnt= (rcnt>file->_cnt)? file->_cnt:rcnt;
4499 memcpy(ptr, file->_ptr, pcnt);
4500 file->_cnt -= pcnt;
4501 file->_ptr += pcnt;
4502 read += pcnt ;
4503 rcnt -= pcnt ;
4504 ptr = (char*)ptr + pcnt;
4505 } else if(!(file->_flag & _IOREAD )) {
4506 if(file->_flag & _IORW) {
4507 file->_flag |= _IOREAD;
4508 } else {
4509 return 0;
4513 if(rcnt>0 && !(file->_flag & (MSVCRT__NOBUF | _IOMYBUF | MSVCRT__USERBUF)))
4514 msvcrt_alloc_buffer(file);
4516 while(rcnt>0)
4518 int i;
4519 if (!file->_cnt && rcnt<file->_bufsiz && (file->_flag & (_IOMYBUF | MSVCRT__USERBUF))) {
4520 i = _read(file->_file, file->_base, file->_bufsiz);
4521 file->_ptr = file->_base;
4522 if (i != -1) {
4523 file->_cnt = i;
4524 if (i > rcnt) i = rcnt;
4526 /* If the buffer fill reaches eof but fread wouldn't, clear eof. */
4527 if (i > 0 && i < file->_cnt) {
4528 get_ioinfo_nolock(file->_file)->wxflag &= ~WX_ATEOF;
4529 file->_flag &= ~_IOEOF;
4531 if (i > 0) {
4532 memcpy(ptr, file->_ptr, i);
4533 file->_cnt -= i;
4534 file->_ptr += i;
4536 } else if (rcnt > INT_MAX) {
4537 i = _read(file->_file, ptr, INT_MAX);
4538 } else if (rcnt < (file->_bufsiz ? file->_bufsiz : MSVCRT_INTERNAL_BUFSIZ)) {
4539 i = _read(file->_file, ptr, rcnt);
4540 } else {
4541 i = _read(file->_file, ptr, rcnt - rcnt % (file->_bufsiz ? file->_bufsiz : MSVCRT_INTERNAL_BUFSIZ));
4543 pread += i;
4544 rcnt -= i;
4545 ptr = (char *)ptr+i;
4546 /* expose feof condition in the flags
4547 * MFC tests file->_flag for feof, and doesn't call feof())
4549 if (get_ioinfo_nolock(file->_file)->wxflag & WX_ATEOF)
4550 file->_flag |= _IOEOF;
4551 else if (i == -1)
4553 file->_flag |= _IOERR;
4554 pread = 0;
4555 rcnt = 0;
4557 if (i < 1) break;
4559 read+=pread;
4560 return read / size;
4563 #if _MSVCR_VER >= 80
4565 /*********************************************************************
4566 * fread_s (MSVCR80.@)
4568 size_t CDECL fread_s(void *buf, size_t buf_size, size_t elem_size,
4569 size_t count, FILE *stream)
4571 size_t ret;
4573 if(!MSVCRT_CHECK_PMT(stream != NULL)) {
4574 if(buf && buf_size)
4575 memset(buf, 0, buf_size);
4576 return 0;
4578 if(!elem_size || !count) return 0;
4580 _lock_file(stream);
4581 ret = _fread_nolock_s(buf, buf_size, elem_size, count, stream);
4582 _unlock_file(stream);
4584 return ret;
4587 /*********************************************************************
4588 * _fread_nolock_s (MSVCR80.@)
4590 size_t CDECL _fread_nolock_s(void *buf, size_t buf_size, size_t elem_size,
4591 size_t count, FILE *stream)
4593 size_t bytes_left, buf_pos;
4595 TRACE("(%p %Iu %Iu %Iu %p)\n", buf, buf_size, elem_size, count, stream);
4597 if(!MSVCRT_CHECK_PMT(stream != NULL)) {
4598 if(buf && buf_size)
4599 memset(buf, 0, buf_size);
4600 return 0;
4602 if(!elem_size || !count) return 0;
4603 if(!MSVCRT_CHECK_PMT(buf != NULL)) return 0;
4604 if(!MSVCRT_CHECK_PMT(SIZE_MAX/count >= elem_size)) return 0;
4606 bytes_left = elem_size*count;
4607 buf_pos = 0;
4608 while(bytes_left) {
4609 if(stream->_cnt > 0) {
4610 size_t size = bytes_left<stream->_cnt ? bytes_left : stream->_cnt;
4612 if(!MSVCRT_CHECK_PMT_ERR(size <= buf_size-buf_pos, ERANGE)) {
4613 memset(buf, 0, buf_size);
4614 return 0;
4617 _fread_nolock((char*)buf+buf_pos, 1, size, stream);
4618 buf_pos += size;
4619 bytes_left -= size;
4620 }else {
4621 int c = _filbuf(stream);
4623 if(c == EOF)
4624 break;
4626 if(!MSVCRT_CHECK_PMT_ERR(buf_size != buf_pos, ERANGE)) {
4627 memset(buf, 0, buf_size);
4628 return 0;
4631 ((char*)buf)[buf_pos++] = c;
4632 bytes_left--;
4636 return buf_pos/elem_size;
4639 #endif /* _MSVCR_VER >= 80 */
4641 /*********************************************************************
4642 * _wfreopen (MSVCRT.@)
4645 FILE* CDECL _wfreopen(const wchar_t *path, const wchar_t *mode, FILE* file)
4647 int open_flags, stream_flags, fd;
4649 TRACE(":path (%s) mode (%s) file (%p) fd (%d)\n", debugstr_w(path), debugstr_w(mode), file, file ? file->_file : -1);
4651 LOCK_FILES();
4652 if (file)
4654 fclose(file);
4655 if (msvcrt_get_flags(mode, &open_flags, &stream_flags) == -1)
4656 file = NULL;
4657 else if((fd = _wopen(path, open_flags, _S_IREAD | _S_IWRITE)) < 0)
4658 file = NULL;
4659 else if(msvcrt_init_fp(file, fd, stream_flags) == -1)
4661 file->_flag = 0;
4662 file = NULL;
4665 UNLOCK_FILES();
4666 return file;
4669 /*********************************************************************
4670 * _wfreopen_s (MSVCRT.@)
4672 int CDECL _wfreopen_s(FILE** pFile,
4673 const wchar_t *path, const wchar_t *mode, FILE* file)
4675 if (!MSVCRT_CHECK_PMT(pFile != NULL)) return EINVAL;
4676 if (!MSVCRT_CHECK_PMT(path != NULL)) return EINVAL;
4677 if (!MSVCRT_CHECK_PMT(mode != NULL)) return EINVAL;
4678 if (!MSVCRT_CHECK_PMT(file != NULL)) return EINVAL;
4680 *pFile = _wfreopen(path, mode, file);
4682 if(!*pFile)
4683 return *_errno();
4684 return 0;
4687 /*********************************************************************
4688 * freopen (MSVCRT.@)
4691 FILE* CDECL freopen(const char *path, const char *mode, FILE* file)
4693 FILE *ret;
4694 wchar_t *pathW = NULL, *modeW = NULL;
4696 if (path && !(pathW = msvcrt_wstrdupa(path))) return NULL;
4697 if (mode && !(modeW = msvcrt_wstrdupa(mode)))
4699 free(pathW);
4700 return NULL;
4703 ret = _wfreopen(pathW, modeW, file);
4705 free(pathW);
4706 free(modeW);
4707 return ret;
4710 /*********************************************************************
4711 * freopen_s (MSVCRT.@)
4713 errno_t CDECL freopen_s(FILE** pFile,
4714 const char *path, const char *mode, FILE* file)
4716 if (!MSVCRT_CHECK_PMT(pFile != NULL)) return EINVAL;
4717 if (!MSVCRT_CHECK_PMT(path != NULL)) return EINVAL;
4718 if (!MSVCRT_CHECK_PMT(mode != NULL)) return EINVAL;
4719 if (!MSVCRT_CHECK_PMT(file != NULL)) return EINVAL;
4721 *pFile = freopen(path, mode, file);
4723 if(!*pFile)
4724 return *_errno();
4725 return 0;
4728 /*********************************************************************
4729 * fsetpos (MSVCRT.@)
4731 int CDECL fsetpos(FILE* file, fpos_t *pos)
4733 return _fseeki64(file,*pos,SEEK_SET);
4736 /*********************************************************************
4737 * _ftelli64 (MSVCRT.@)
4739 __int64 CDECL _ftelli64(FILE* file)
4741 __int64 ret;
4743 _lock_file(file);
4744 ret = _ftelli64_nolock(file);
4745 _unlock_file(file);
4747 return ret;
4750 /*********************************************************************
4751 * _ftelli64_nolock (MSVCRT.@)
4753 __int64 CDECL _ftelli64_nolock(FILE* file)
4755 __int64 pos;
4757 pos = _telli64(file->_file);
4758 if(pos == -1)
4759 return -1;
4760 if(file->_flag & (_IOMYBUF | MSVCRT__USERBUF)) {
4761 if(file->_flag & _IOWRT) {
4762 pos += file->_ptr - file->_base;
4764 if(get_ioinfo_nolock(file->_file)->wxflag & WX_TEXT) {
4765 char *p;
4767 for(p=file->_base; p<file->_ptr; p++)
4768 if(*p == '\n')
4769 pos++;
4771 } else if(!file->_cnt) { /* nothing to do */
4772 } else if(_lseeki64(file->_file, 0, SEEK_END)==pos) {
4773 int i;
4775 pos -= file->_cnt;
4776 if(get_ioinfo_nolock(file->_file)->wxflag & WX_TEXT) {
4777 for(i=0; i<file->_cnt; i++)
4778 if(file->_ptr[i] == '\n')
4779 pos--;
4781 } else {
4782 char *p;
4784 if(_lseeki64(file->_file, pos, SEEK_SET) != pos)
4785 return -1;
4787 pos -= file->_bufsiz;
4788 pos += file->_ptr - file->_base;
4790 if(get_ioinfo_nolock(file->_file)->wxflag & WX_TEXT) {
4791 if(get_ioinfo_nolock(file->_file)->wxflag & WX_READNL)
4792 pos--;
4794 for(p=file->_base; p<file->_ptr; p++)
4795 if(*p == '\n')
4796 pos++;
4801 return pos;
4804 /*********************************************************************
4805 * ftell (MSVCRT.@)
4807 __msvcrt_long CDECL ftell(FILE* file)
4809 return _ftelli64(file);
4812 #if _MSVCR_VER >= 80
4813 /*********************************************************************
4814 * _ftell_nolock (MSVCR80.@)
4816 __msvcrt_long CDECL _ftell_nolock(FILE* file)
4818 return _ftelli64_nolock(file);
4820 #endif
4822 /*********************************************************************
4823 * fgetpos (MSVCRT.@)
4825 int CDECL fgetpos(FILE* file, fpos_t *pos)
4827 *pos = _ftelli64(file);
4828 if(*pos == -1)
4829 return -1;
4830 return 0;
4833 /*********************************************************************
4834 * fputs (MSVCRT.@)
4836 int CDECL fputs(const char *s, FILE* file)
4838 size_t len = strlen(s);
4839 int ret;
4841 _lock_file(file);
4842 ret = _fwrite_nolock(s, sizeof(*s), len, file) == len ? 0 : EOF;
4843 _unlock_file(file);
4844 return ret;
4847 /*********************************************************************
4848 * fputws (MSVCRT.@)
4850 int CDECL fputws(const wchar_t *s, FILE* file)
4852 size_t i, len = wcslen(s);
4853 BOOL tmp_buf;
4854 int ret;
4856 _lock_file(file);
4857 if (!(get_ioinfo_nolock(file->_file)->wxflag & WX_TEXT)) {
4858 ret = _fwrite_nolock(s,sizeof(*s),len,file) == len ? 0 : EOF;
4859 _unlock_file(file);
4860 return ret;
4863 tmp_buf = add_std_buffer(file);
4864 for (i=0; i<len; i++) {
4865 if(_fputwc_nolock(s[i], file) == WEOF) {
4866 if(tmp_buf) remove_std_buffer(file);
4867 _unlock_file(file);
4868 return WEOF;
4872 if(tmp_buf) remove_std_buffer(file);
4873 _unlock_file(file);
4874 return 0;
4877 /*********************************************************************
4878 * getchar (MSVCRT.@)
4880 int CDECL getchar(void)
4882 return fgetc(stdin);
4885 /*********************************************************************
4886 * getc (MSVCRT.@)
4888 int CDECL getc(FILE* file)
4890 return fgetc(file);
4893 /*********************************************************************
4894 * gets_s (MSVCR80.@)
4896 char * CDECL gets_s(char *buf, size_t len)
4898 char *buf_start = buf;
4899 int cc;
4901 if (!MSVCRT_CHECK_PMT(buf != NULL)) return NULL;
4902 if (!MSVCRT_CHECK_PMT(len != 0)) return NULL;
4904 _lock_file(stdin);
4905 for(cc = _fgetc_nolock(stdin);
4906 len != 0 && cc != EOF && cc != '\n';
4907 cc = _fgetc_nolock(stdin))
4909 if (cc != '\r')
4911 *buf++ = (char)cc;
4912 len--;
4915 _unlock_file(stdin);
4917 if (!len)
4919 *buf_start = 0;
4920 _invalid_parameter(NULL, NULL, NULL, 0, 0);
4921 return NULL;
4924 if ((cc == EOF) && (buf_start == buf))
4926 TRACE(":nothing read\n");
4927 return NULL;
4929 *buf = '\0';
4931 TRACE("got '%s'\n", buf_start);
4932 return buf_start;
4935 /*********************************************************************
4936 * gets (MSVCRT.@)
4938 char * CDECL gets(char *buf)
4940 return gets_s(buf, -1);
4943 /*********************************************************************
4944 * _getws (MSVCRT.@)
4946 wchar_t* CDECL _getws(wchar_t* buf)
4948 wint_t cc;
4949 wchar_t* ws = buf;
4951 _lock_file(stdin);
4952 for (cc = _fgetwc_nolock(stdin); cc != WEOF && cc != '\n';
4953 cc = _fgetwc_nolock(stdin))
4955 if (cc != '\r')
4956 *buf++ = (wchar_t)cc;
4958 _unlock_file(stdin);
4960 if ((cc == WEOF) && (ws == buf))
4962 TRACE(":nothing read\n");
4963 return NULL;
4965 *buf = '\0';
4967 TRACE("got %s\n", debugstr_w(ws));
4968 return ws;
4971 /*********************************************************************
4972 * putc (MSVCRT.@)
4974 int CDECL putc(int c, FILE* file)
4976 return fputc(c, file);
4979 /*********************************************************************
4980 * putchar (MSVCRT.@)
4982 int CDECL putchar(int c)
4984 return fputc(c, stdout);
4987 /*********************************************************************
4988 * puts (MSVCRT.@)
4990 int CDECL puts(const char *s)
4992 size_t len = strlen(s);
4993 int ret;
4995 _lock_file(stdout);
4996 if(_fwrite_nolock(s, sizeof(*s), len, stdout) != len) {
4997 _unlock_file(stdout);
4998 return EOF;
5001 ret = _fwrite_nolock("\n",1,1,stdout) == 1 ? 0 : EOF;
5002 _unlock_file(stdout);
5003 return ret;
5006 /*********************************************************************
5007 * _putws (MSVCRT.@)
5009 int CDECL _putws(const wchar_t *s)
5011 int ret;
5013 _lock_file(stdout);
5014 ret = fputws(s, stdout);
5015 if(ret >= 0)
5016 ret = _fputwc_nolock('\n', stdout);
5017 _unlock_file(stdout);
5018 return ret >= 0 ? 0 : WEOF;
5021 /*********************************************************************
5022 * remove (MSVCRT.@)
5024 int CDECL remove(const char *path)
5026 TRACE("(%s)\n", path);
5027 if (DeleteFileA(path))
5028 return 0;
5029 TRACE(":failed (%ld)\n", GetLastError());
5030 msvcrt_set_errno(GetLastError());
5031 return -1;
5034 /*********************************************************************
5035 * _wremove (MSVCRT.@)
5037 int CDECL _wremove(const wchar_t *path)
5039 TRACE("(%s)\n", debugstr_w(path));
5040 if (DeleteFileW(path))
5041 return 0;
5042 TRACE(":failed (%ld)\n", GetLastError());
5043 msvcrt_set_errno(GetLastError());
5044 return -1;
5047 /*********************************************************************
5048 * rename (MSVCRT.@)
5050 int CDECL rename(const char *oldpath,const char *newpath)
5052 TRACE(":from %s to %s\n", oldpath, newpath);
5053 if (MoveFileExA(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
5054 return 0;
5055 TRACE(":failed (%ld)\n", GetLastError());
5056 msvcrt_set_errno(GetLastError());
5057 return -1;
5060 /*********************************************************************
5061 * _wrename (MSVCRT.@)
5063 int CDECL _wrename(const wchar_t *oldpath,const wchar_t *newpath)
5065 TRACE(":from %s to %s\n", debugstr_w(oldpath), debugstr_w(newpath));
5066 if (MoveFileExW(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
5067 return 0;
5068 TRACE(":failed (%ld)\n", GetLastError());
5069 msvcrt_set_errno(GetLastError());
5070 return -1;
5073 /*********************************************************************
5074 * setvbuf (MSVCRT.@)
5076 int CDECL setvbuf(FILE* file, char *buf, int mode, size_t size)
5078 if(!MSVCRT_CHECK_PMT(file != NULL)) return -1;
5079 if(!MSVCRT_CHECK_PMT(mode==_IONBF || mode==_IOFBF || mode==_IOLBF)) return -1;
5080 if(!MSVCRT_CHECK_PMT(mode==_IONBF || (size>=2 && size<=INT_MAX))) return -1;
5082 _lock_file(file);
5084 _fflush_nolock(file);
5085 if(file->_flag & _IOMYBUF)
5086 free(file->_base);
5087 file->_flag &= ~(MSVCRT__NOBUF | _IOMYBUF | MSVCRT__USERBUF);
5088 file->_cnt = 0;
5090 if(mode == _IONBF) {
5091 file->_flag |= MSVCRT__NOBUF;
5092 file->_base = file->_ptr = (char*)&file->_charbuf;
5093 file->_bufsiz = 2;
5094 }else if(buf) {
5095 file->_base = file->_ptr = buf;
5096 file->_flag |= MSVCRT__USERBUF;
5097 file->_bufsiz = size;
5098 }else {
5099 file->_base = file->_ptr = malloc(size);
5100 if(!file->_base) {
5101 file->_bufsiz = 0;
5102 _unlock_file(file);
5103 return -1;
5106 file->_flag |= _IOMYBUF;
5107 file->_bufsiz = size;
5109 _unlock_file(file);
5110 return 0;
5113 /*********************************************************************
5114 * setbuf (MSVCRT.@)
5116 void CDECL setbuf(FILE* file, char *buf)
5118 setvbuf(file, buf, buf ? _IOFBF : _IONBF, BUFSIZ);
5121 static int tmpnam_helper(char *s, size_t size, LONG *tmpnam_unique, int tmp_max)
5123 char tmpstr[8];
5124 char *p = s;
5125 int digits;
5127 if (!MSVCRT_CHECK_PMT(s != NULL)) return EINVAL;
5129 if (size < 3) {
5130 if (size) *s = 0;
5131 *_errno() = ERANGE;
5132 return ERANGE;
5134 *p++ = '\\';
5135 *p++ = 's';
5136 size -= 2;
5137 digits = msvcrt_int_to_base32(GetCurrentProcessId(), tmpstr);
5138 if (digits+1 > size) {
5139 *s = 0;
5140 *_errno() = ERANGE;
5141 return ERANGE;
5143 memcpy(p, tmpstr, digits*sizeof(tmpstr[0]));
5144 p += digits;
5145 *p++ = '.';
5146 size -= digits+1;
5148 while(1) {
5149 while ((digits = *tmpnam_unique)+1 < tmp_max) {
5150 if (InterlockedCompareExchange(tmpnam_unique, digits+1, digits) == digits)
5151 break;
5154 digits = msvcrt_int_to_base32(digits, tmpstr);
5155 if (digits+1 > size) {
5156 *s = 0;
5157 *_errno() = ERANGE;
5158 return ERANGE;
5160 memcpy(p, tmpstr, digits*sizeof(tmpstr[0]));
5161 p[digits] = 0;
5163 if (GetFileAttributesA(s) == INVALID_FILE_ATTRIBUTES &&
5164 GetLastError() == ERROR_FILE_NOT_FOUND)
5165 break;
5167 return 0;
5170 int CDECL tmpnam_s(char *s, size_t size)
5172 return tmpnam_helper(s, size, &tmpnam_s_unique, TMP_MAX_S);
5175 /*********************************************************************
5176 * tmpnam (MSVCRT.@)
5178 char * CDECL tmpnam(char *s)
5180 if (!s) {
5181 thread_data_t *data = msvcrt_get_thread_data();
5183 if(!data->tmpnam_buffer)
5184 data->tmpnam_buffer = malloc(MAX_PATH);
5186 s = data->tmpnam_buffer;
5189 return tmpnam_helper(s, -1, &tmpnam_unique, TMP_MAX) ? NULL : s;
5192 static int wtmpnam_helper(wchar_t *s, size_t size, LONG *tmpnam_unique, int tmp_max)
5194 wchar_t tmpstr[8];
5195 wchar_t *p = s;
5196 int digits;
5198 if (!MSVCRT_CHECK_PMT(s != NULL)) return EINVAL;
5200 if (size < 3) {
5201 if (size) *s = 0;
5202 *_errno() = ERANGE;
5203 return ERANGE;
5205 *p++ = '\\';
5206 *p++ = 's';
5207 size -= 2;
5208 digits = msvcrt_int_to_base32_w(GetCurrentProcessId(), tmpstr);
5209 if (digits+1 > size) {
5210 *s = 0;
5211 *_errno() = ERANGE;
5212 return ERANGE;
5214 memcpy(p, tmpstr, digits*sizeof(tmpstr[0]));
5215 p += digits;
5216 *p++ = '.';
5217 size -= digits+1;
5219 while(1) {
5220 while ((digits = *tmpnam_unique)+1 < tmp_max) {
5221 if (InterlockedCompareExchange(tmpnam_unique, digits+1, digits) == digits)
5222 break;
5225 digits = msvcrt_int_to_base32_w(digits, tmpstr);
5226 if (digits+1 > size) {
5227 *s = 0;
5228 *_errno() = ERANGE;
5229 return ERANGE;
5231 memcpy(p, tmpstr, digits*sizeof(tmpstr[0]));
5232 p[digits] = 0;
5234 if (GetFileAttributesW(s) == INVALID_FILE_ATTRIBUTES &&
5235 GetLastError() == ERROR_FILE_NOT_FOUND)
5236 break;
5238 return 0;
5241 /*********************************************************************
5242 * _wtmpnam_s (MSVCRT.@)
5244 int CDECL _wtmpnam_s(wchar_t *s, size_t size)
5246 return wtmpnam_helper(s, size, &tmpnam_s_unique, TMP_MAX_S);
5249 /*********************************************************************
5250 * _wtmpnam (MSVCRT.@)
5252 wchar_t * CDECL _wtmpnam(wchar_t *s)
5254 if (!s) {
5255 thread_data_t *data = msvcrt_get_thread_data();
5257 if(!data->wtmpnam_buffer)
5258 data->wtmpnam_buffer = malloc(sizeof(wchar_t[MAX_PATH]));
5260 s = data->wtmpnam_buffer;
5263 return wtmpnam_helper(s, -1, &tmpnam_unique, TMP_MAX) ? NULL : s;
5266 /*********************************************************************
5267 * tmpfile (MSVCRT.@)
5269 FILE* CDECL tmpfile(void)
5271 char *filename = _tempnam(",", "t");
5272 int fd;
5273 FILE* file = NULL;
5275 LOCK_FILES();
5276 fd = _open(filename, _O_CREAT | _O_BINARY | _O_RDWR | _O_TEMPORARY,
5277 _S_IREAD | _S_IWRITE);
5278 if (fd != -1 && (file = msvcrt_alloc_fp()))
5280 if (msvcrt_init_fp(file, fd, _IORW) == -1)
5282 file->_flag = 0;
5283 file = NULL;
5285 else file->_tmpfname = _strdup(filename);
5288 if(fd != -1 && !file)
5289 _close(fd);
5290 free(filename);
5291 UNLOCK_FILES();
5292 return file;
5295 /*********************************************************************
5296 * tmpfile_s (MSVCRT.@)
5298 int CDECL tmpfile_s(FILE** file)
5300 if (!MSVCRT_CHECK_PMT(file != NULL)) return EINVAL;
5302 *file = tmpfile();
5303 return 0;
5306 static int puts_clbk_file_a(void *file, int len, const char *str)
5308 return fwrite(str, sizeof(char), len, file);
5311 static int puts_clbk_file_w(void *file, int len, const wchar_t *str)
5313 int i, ret;
5315 _lock_file(file);
5317 if(!(get_ioinfo_nolock(((FILE*)file)->_file)->wxflag & WX_TEXT)) {
5318 ret = _fwrite_nolock(str, sizeof(wchar_t), len, file);
5319 _unlock_file(file);
5320 return ret;
5323 for(i=0; i<len; i++) {
5324 if(_fputwc_nolock(str[i], file) == WEOF) {
5325 _unlock_file(file);
5326 return -1;
5330 _unlock_file(file);
5331 return len;
5334 static int vfprintf_helper(DWORD options, FILE* file, const char *format,
5335 _locale_t locale, va_list valist)
5337 printf_arg args_ctx[_ARGMAX+1];
5338 BOOL tmp_buf;
5339 int ret;
5341 if(!MSVCRT_CHECK_PMT( file != NULL )) return -1;
5342 if(!MSVCRT_CHECK_PMT( format != NULL )) return -1;
5344 if(options & MSVCRT_PRINTF_POSITIONAL_PARAMS) {
5345 memset(args_ctx, 0, sizeof(args_ctx));
5346 ret = create_positional_ctx_a(args_ctx, format, valist);
5347 if(ret < 0) {
5348 _invalid_parameter(NULL, NULL, NULL, 0, 0);
5349 *_errno() = EINVAL;
5350 return ret;
5351 } else if(!ret)
5352 options &= ~MSVCRT_PRINTF_POSITIONAL_PARAMS;
5355 _lock_file(file);
5356 tmp_buf = add_std_buffer(file);
5357 ret = pf_printf_a(puts_clbk_file_a, file, format, locale, options,
5358 options & MSVCRT_PRINTF_POSITIONAL_PARAMS ? arg_clbk_positional : arg_clbk_valist,
5359 options & MSVCRT_PRINTF_POSITIONAL_PARAMS ? args_ctx : NULL, &valist);
5360 if(tmp_buf) remove_std_buffer(file);
5361 _unlock_file(file);
5363 return ret;
5366 static int vfwprintf_helper(DWORD options, FILE* file, const wchar_t *format,
5367 _locale_t locale, va_list valist)
5369 printf_arg args_ctx[_ARGMAX+1];
5370 BOOL tmp_buf;
5371 int ret;
5373 if(!MSVCRT_CHECK_PMT( file != NULL )) return -1;
5374 if(!MSVCRT_CHECK_PMT( format != NULL )) return -1;
5376 if(options & MSVCRT_PRINTF_POSITIONAL_PARAMS) {
5377 memset(args_ctx, 0, sizeof(args_ctx));
5378 ret = create_positional_ctx_w(args_ctx, format, valist);
5379 if(ret < 0) {
5380 _invalid_parameter(NULL, NULL, NULL, 0, 0);
5381 *_errno() = EINVAL;
5382 return ret;
5383 } else if(!ret)
5384 options &= ~MSVCRT_PRINTF_POSITIONAL_PARAMS;
5387 _lock_file(file);
5388 tmp_buf = add_std_buffer(file);
5389 ret = pf_printf_w(puts_clbk_file_w, file, format, locale, options,
5390 options & MSVCRT_PRINTF_POSITIONAL_PARAMS ? arg_clbk_positional : arg_clbk_valist,
5391 options & MSVCRT_PRINTF_POSITIONAL_PARAMS ? args_ctx : NULL, &valist);
5392 if(tmp_buf) remove_std_buffer(file);
5393 _unlock_file(file);
5395 return ret;
5398 /*********************************************************************
5399 * _vfprintf_s_l (MSVCRT.@)
5401 int CDECL _vfprintf_s_l(FILE* file, const char *format,
5402 _locale_t locale, va_list valist)
5404 return vfprintf_helper(MSVCRT_PRINTF_INVOKE_INVALID_PARAM_HANDLER, file, format, locale, valist);
5407 /*********************************************************************
5408 * _vfwprintf_s_l (MSVCRT.@)
5410 int CDECL _vfwprintf_s_l(FILE* file, const wchar_t *format,
5411 _locale_t locale, va_list valist)
5413 return vfwprintf_helper(MSVCRT_PRINTF_INVOKE_INVALID_PARAM_HANDLER, file, format, locale, valist);
5416 /*********************************************************************
5417 * vfprintf (MSVCRT.@)
5419 int CDECL vfprintf(FILE* file, const char *format, va_list valist)
5421 return vfprintf_helper(0, file, format, NULL, valist);
5424 /*********************************************************************
5425 * vfprintf_s (MSVCRT.@)
5427 int CDECL vfprintf_s(FILE* file, const char *format, va_list valist)
5429 return _vfprintf_s_l(file, format, NULL, valist);
5432 /*********************************************************************
5433 * vfwprintf (MSVCRT.@)
5435 int CDECL vfwprintf(FILE* file, const wchar_t *format, va_list valist)
5437 return vfwprintf_helper(0, file, format, NULL, valist);
5440 /*********************************************************************
5441 * vfwprintf_s (MSVCRT.@)
5443 int CDECL vfwprintf_s(FILE* file, const wchar_t *format, va_list valist)
5445 return _vfwprintf_s_l(file, format, NULL, valist);
5448 #if _MSVCR_VER >= 140
5450 /*********************************************************************
5451 * __stdio_common_vfprintf (UCRTBASE.@)
5453 int CDECL _stdio_common_vfprintf(unsigned __int64 options, FILE *file, const char *format,
5454 _locale_t locale, va_list valist)
5456 if (options & ~UCRTBASE_PRINTF_MASK)
5457 FIXME("options %#I64x not handled\n", options);
5459 return vfprintf_helper(options & UCRTBASE_PRINTF_MASK, file, format, locale, valist);
5462 /*********************************************************************
5463 * __stdio_common_vfprintf_p (UCRTBASE.@)
5465 int CDECL __stdio_common_vfprintf_p(unsigned __int64 options, FILE *file, const char *format,
5466 _locale_t locale, va_list valist)
5468 if (options & ~UCRTBASE_PRINTF_MASK)
5469 FIXME("options %#I64x not handled\n", options);
5471 return vfprintf_helper((options & UCRTBASE_PRINTF_MASK) | MSVCRT_PRINTF_POSITIONAL_PARAMS
5472 | MSVCRT_PRINTF_INVOKE_INVALID_PARAM_HANDLER, file, format, locale, valist);
5476 /*********************************************************************
5477 * __stdio_common_vfprintf_s (UCRTBASE.@)
5479 int CDECL __stdio_common_vfprintf_s(unsigned __int64 options, FILE *file, const char *format,
5480 _locale_t locale, va_list valist)
5482 if (options & ~UCRTBASE_PRINTF_MASK)
5483 FIXME("options %#I64x not handled\n", options);
5485 return vfprintf_helper((options & UCRTBASE_PRINTF_MASK) | MSVCRT_PRINTF_INVOKE_INVALID_PARAM_HANDLER,
5486 file, format, locale, valist);
5489 /*********************************************************************
5490 * __stdio_common_vfwprintf (UCRTBASE.@)
5492 int CDECL __stdio_common_vfwprintf(unsigned __int64 options, FILE *file, const wchar_t *format,
5493 _locale_t locale, va_list valist)
5495 if (options & ~UCRTBASE_PRINTF_MASK)
5496 FIXME("options %#I64x not handled\n", options);
5498 return vfwprintf_helper(options & UCRTBASE_PRINTF_MASK, file, format, locale, valist);
5501 /*********************************************************************
5502 * __stdio_common_vfwprintf_p (UCRTBASE.@)
5504 int CDECL __stdio_common_vfwprintf_p(unsigned __int64 options, FILE *file, const wchar_t *format,
5505 _locale_t locale, va_list valist)
5507 if (options & ~UCRTBASE_PRINTF_MASK)
5508 FIXME("options %#I64x not handled\n", options);
5510 return vfwprintf_helper((options & UCRTBASE_PRINTF_MASK) | MSVCRT_PRINTF_POSITIONAL_PARAMS
5511 | MSVCRT_PRINTF_INVOKE_INVALID_PARAM_HANDLER, file, format, locale, valist);
5515 /*********************************************************************
5516 * __stdio_common_vfwprintf_s (UCRTBASE.@)
5518 int CDECL __stdio_common_vfwprintf_s(unsigned __int64 options, FILE *file, const wchar_t *format,
5519 _locale_t locale, va_list valist)
5521 if (options & ~UCRTBASE_PRINTF_MASK)
5522 FIXME("options %#I64x not handled\n", options);
5524 return vfwprintf_helper((options & UCRTBASE_PRINTF_MASK) | MSVCRT_PRINTF_INVOKE_INVALID_PARAM_HANDLER,
5525 file, format, locale, valist);
5528 #endif /* _MSVCR_VER >= 140 */
5530 /*********************************************************************
5531 * _vfprintf_l (MSVCRT.@)
5533 int CDECL _vfprintf_l(FILE* file, const char *format,
5534 _locale_t locale, va_list valist)
5536 return vfprintf_helper(0, file, format, locale, valist);
5539 /*********************************************************************
5540 * _vfwprintf_l (MSVCRT.@)
5542 int CDECL _vfwprintf_l(FILE* file, const wchar_t *format,
5543 _locale_t locale, va_list valist)
5545 return vfwprintf_helper(0, file, format, locale, valist);
5548 /*********************************************************************
5549 * _vfprintf_p_l (MSVCRT.@)
5551 int CDECL _vfprintf_p_l(FILE* file, const char *format,
5552 _locale_t locale, va_list valist)
5554 return vfprintf_helper(MSVCRT_PRINTF_POSITIONAL_PARAMS | MSVCRT_PRINTF_INVOKE_INVALID_PARAM_HANDLER,
5555 file, format, locale, valist);
5558 /*********************************************************************
5559 * _vfprintf_p (MSVCRT.@)
5561 int CDECL _vfprintf_p(FILE* file, const char *format, va_list valist)
5563 return _vfprintf_p_l(file, format, NULL, valist);
5566 /*********************************************************************
5567 * _vfwprintf_p_l (MSVCRT.@)
5569 int CDECL _vfwprintf_p_l(FILE* file, const wchar_t *format,
5570 _locale_t locale, va_list valist)
5572 return vfwprintf_helper(MSVCRT_PRINTF_POSITIONAL_PARAMS | MSVCRT_PRINTF_INVOKE_INVALID_PARAM_HANDLER,
5573 file, format, locale, valist);
5576 /*********************************************************************
5577 * _vfwprintf_p (MSVCRT.@)
5579 int CDECL _vfwprintf_p(FILE* file, const wchar_t *format, va_list valist)
5581 return _vfwprintf_p_l(file, format, NULL, valist);
5584 /*********************************************************************
5585 * vprintf (MSVCRT.@)
5587 int CDECL vprintf(const char *format, va_list valist)
5589 return vfprintf(stdout,format,valist);
5592 /*********************************************************************
5593 * vprintf_s (MSVCRT.@)
5595 int CDECL vprintf_s(const char *format, va_list valist)
5597 return vfprintf_s(stdout,format,valist);
5600 /*********************************************************************
5601 * vwprintf (MSVCRT.@)
5603 int CDECL vwprintf(const wchar_t *format, va_list valist)
5605 return vfwprintf(stdout,format,valist);
5608 /*********************************************************************
5609 * vwprintf_s (MSVCRT.@)
5611 int CDECL vwprintf_s(const wchar_t *format, va_list valist)
5613 return vfwprintf_s(stdout,format,valist);
5616 /*********************************************************************
5617 * fprintf (MSVCRT.@)
5619 int WINAPIV fprintf(FILE* file, const char *format, ...)
5621 va_list valist;
5622 int res;
5623 va_start(valist, format);
5624 res = vfprintf(file, format, valist);
5625 va_end(valist);
5626 return res;
5629 /*********************************************************************
5630 * fprintf_s (MSVCRT.@)
5632 int WINAPIV fprintf_s(FILE* file, const char *format, ...)
5634 va_list valist;
5635 int res;
5636 va_start(valist, format);
5637 res = vfprintf_s(file, format, valist);
5638 va_end(valist);
5639 return res;
5642 /*********************************************************************
5643 * _fprintf_l (MSVCRT.@)
5645 int WINAPIV _fprintf_l(FILE* file, const char *format, _locale_t locale, ...)
5647 va_list valist;
5648 int res;
5649 va_start(valist, locale);
5650 res = _vfprintf_l(file, format, locale, valist);
5651 va_end(valist);
5652 return res;
5656 /*********************************************************************
5657 * _fprintf_p (MSVCRT.@)
5659 int WINAPIV _fprintf_p(FILE* file, const char *format, ...)
5661 va_list valist;
5662 int res;
5663 va_start(valist, format);
5664 res = _vfprintf_p_l(file, format, NULL, valist);
5665 va_end(valist);
5666 return res;
5669 /*********************************************************************
5670 * _fprintf_p_l (MSVCRT.@)
5672 int WINAPIV _fprintf_p_l(FILE* file, const char *format, _locale_t locale, ...)
5674 va_list valist;
5675 int res;
5676 va_start(valist, locale);
5677 res = _vfprintf_p_l(file, format, locale, valist);
5678 va_end(valist);
5679 return res;
5682 /*********************************************************************
5683 * _fprintf_s_l (MSVCRT.@)
5685 int WINAPIV _fprintf_s_l(FILE* file, const char *format, _locale_t locale, ...)
5687 va_list valist;
5688 int res;
5689 va_start(valist, locale);
5690 res = _vfprintf_s_l(file, format, locale, valist);
5691 va_end(valist);
5692 return res;
5695 /*********************************************************************
5696 * fwprintf (MSVCRT.@)
5698 int WINAPIV fwprintf(FILE* file, const wchar_t *format, ...)
5700 va_list valist;
5701 int res;
5702 va_start(valist, format);
5703 res = vfwprintf(file, format, valist);
5704 va_end(valist);
5705 return res;
5708 /*********************************************************************
5709 * fwprintf_s (MSVCRT.@)
5711 int WINAPIV fwprintf_s(FILE* file, const wchar_t *format, ...)
5713 va_list valist;
5714 int res;
5715 va_start(valist, format);
5716 res = vfwprintf_s(file, format, valist);
5717 va_end(valist);
5718 return res;
5721 /*********************************************************************
5722 * _fwprintf_l (MSVCRT.@)
5724 int WINAPIV _fwprintf_l(FILE* file, const wchar_t *format, _locale_t locale, ...)
5726 va_list valist;
5727 int res;
5728 va_start(valist, locale);
5729 res = _vfwprintf_l(file, format, locale, valist);
5730 va_end(valist);
5731 return res;
5734 /*********************************************************************
5735 * _fwprintf_p (MSVCRT.@)
5737 int WINAPIV _fwprintf_p(FILE* file, const wchar_t *format, ...)
5739 va_list valist;
5740 int res;
5741 va_start(valist, format);
5742 res = _vfwprintf_p_l(file, format, NULL, valist);
5743 va_end(valist);
5744 return res;
5747 /*********************************************************************
5748 * _fwprintf_p_l (MSVCRT.@)
5750 int WINAPIV _fwprintf_p_l(FILE* file, const wchar_t *format, _locale_t locale, ...)
5752 va_list valist;
5753 int res;
5754 va_start(valist, locale);
5755 res = _vfwprintf_p_l(file, format, locale, valist);
5756 va_end(valist);
5757 return res;
5760 /*********************************************************************
5761 * _fwprintf_s_l (MSVCRT.@)
5763 int WINAPIV _fwprintf_s_l(FILE* file, const wchar_t *format, _locale_t locale, ...)
5765 va_list valist;
5766 int res;
5767 va_start(valist, locale);
5768 res = _vfwprintf_s_l(file, format, locale, valist);
5769 va_end(valist);
5770 return res;
5773 /*********************************************************************
5774 * printf (MSVCRT.@)
5776 int WINAPIV printf(const char *format, ...)
5778 va_list valist;
5779 int res;
5780 va_start(valist, format);
5781 res = vfprintf(stdout, format, valist);
5782 va_end(valist);
5783 return res;
5786 /*********************************************************************
5787 * printf_s (MSVCRT.@)
5789 int WINAPIV printf_s(const char *format, ...)
5791 va_list valist;
5792 int res;
5793 va_start(valist, format);
5794 res = vprintf_s(format, valist);
5795 va_end(valist);
5796 return res;
5799 /*********************************************************************
5800 * ungetc (MSVCRT.@)
5802 int CDECL ungetc(int c, FILE * file)
5804 int ret;
5806 if(!MSVCRT_CHECK_PMT(file != NULL)) return EOF;
5808 _lock_file(file);
5809 ret = _ungetc_nolock(c, file);
5810 _unlock_file(file);
5812 return ret;
5815 /*********************************************************************
5816 * _ungetc_nolock (MSVCRT.@)
5818 int CDECL _ungetc_nolock(int c, FILE * file)
5820 if(!MSVCRT_CHECK_PMT(file != NULL)) return EOF;
5822 if (c == EOF || !(file->_flag&_IOREAD ||
5823 (file->_flag&_IORW && !(file->_flag&_IOWRT))))
5824 return EOF;
5826 if((!(file->_flag & (MSVCRT__NOBUF | _IOMYBUF | MSVCRT__USERBUF))
5827 && msvcrt_alloc_buffer(file))
5828 || (!file->_cnt && file->_ptr==file->_base))
5829 file->_ptr++;
5831 if(file->_ptr>file->_base) {
5832 file->_ptr--;
5833 if(file->_flag & _IOSTRG) {
5834 if(*file->_ptr != c) {
5835 file->_ptr++;
5836 return EOF;
5838 }else {
5839 *file->_ptr = c;
5841 file->_cnt++;
5842 file->_flag &= ~(_IOERR | _IOEOF);
5843 file->_flag |= _IOREAD;
5844 return c;
5847 return EOF;
5850 /*********************************************************************
5851 * ungetwc (MSVCRT.@)
5853 wint_t CDECL ungetwc(wint_t wc, FILE * file)
5855 wint_t ret;
5857 if(!MSVCRT_CHECK_PMT(file != NULL)) return WEOF;
5859 _lock_file(file);
5860 ret = _ungetwc_nolock(wc, file);
5861 _unlock_file(file);
5863 return ret;
5866 /*********************************************************************
5867 * _ungetwc_nolock (MSVCRT.@)
5869 wint_t CDECL _ungetwc_nolock(wint_t wc, FILE * file)
5871 wchar_t mwc = wc;
5873 if(!MSVCRT_CHECK_PMT(file != NULL)) return WEOF;
5874 if (wc == WEOF)
5875 return WEOF;
5877 if(ioinfo_get_textmode(get_ioinfo_nolock(file->_file)) != TEXTMODE_ANSI
5878 || !(get_ioinfo_nolock(file->_file)->wxflag & WX_TEXT)) {
5879 unsigned char * pp = (unsigned char *)&mwc;
5880 int i;
5882 for(i=sizeof(wchar_t)-1;i>=0;i--) {
5883 if(pp[i] != _ungetc_nolock(pp[i],file))
5884 return WEOF;
5886 }else {
5887 char mbs[MB_LEN_MAX];
5888 int len;
5890 len = wctomb(mbs, mwc);
5891 if(len == -1)
5892 return WEOF;
5894 for(len--; len>=0; len--) {
5895 if(mbs[len] != _ungetc_nolock(mbs[len], file))
5896 return WEOF;
5900 return mwc;
5903 /*********************************************************************
5904 * wprintf (MSVCRT.@)
5906 int WINAPIV wprintf(const wchar_t *format, ...)
5908 va_list valist;
5909 int res;
5910 va_start(valist, format);
5911 res = vwprintf(format, valist);
5912 va_end(valist);
5913 return res;
5916 /*********************************************************************
5917 * wprintf_s (MSVCRT.@)
5919 int WINAPIV wprintf_s(const wchar_t *format, ...)
5921 va_list valist;
5922 int res;
5923 va_start(valist, format);
5924 res = vwprintf_s(format, valist);
5925 va_end(valist);
5926 return res;
5929 /*********************************************************************
5930 * _getmaxstdio (MSVCRT.@)
5932 int CDECL _getmaxstdio(void)
5934 return MSVCRT_max_streams;
5937 /*********************************************************************
5938 * _setmaxstdio (MSVCRT.@)
5940 int CDECL _setmaxstdio(int newmax)
5942 TRACE("%d\n", newmax);
5944 if(newmax<_IOB_ENTRIES || newmax>MSVCRT_MAX_FILES || newmax<MSVCRT_stream_idx)
5945 return -1;
5947 MSVCRT_max_streams = newmax;
5948 return MSVCRT_max_streams;
5951 #if _MSVCR_VER >= 140
5952 /*********************************************************************
5953 * _get_stream_buffer_pointers (UCRTBASE.@)
5955 int CDECL _get_stream_buffer_pointers(FILE *file, char*** base,
5956 char*** ptr, int** count)
5958 if (base)
5959 *base = &file->_base;
5960 if (ptr)
5961 *ptr = &file->_ptr;
5962 if (count)
5963 *count = &file->_cnt;
5964 return 0;
5966 #endif