- Provide a real fix for fwprintf and fputwc in case the output stream is in TEXT...
[reactos.git] / reactos / lib / sdk / crt / stdio / file.c
1 /*
2 * PROJECT: ReactOS CRT library
3 * LICENSE: LGPL - See COPYING in the top level directory
4 * FILE: lib/sdk/crt/stdio/file.c
5 * PURPOSE: File CRT functions
6 * PROGRAMMERS: Wine team
7 * Ported to ReactOS by Aleksey Bragin (aleksey@reactos.org)
8 */
9
10 /*
11 * msvcrt.dll file functions
12 *
13 * Copyright 1996,1998 Marcus Meissner
14 * Copyright 1996 Jukka Iivonen
15 * Copyright 1997,2000 Uwe Bonnes
16 * Copyright 2000 Jon Griffiths
17 * Copyright 2004 Eric Pouech
18 * Copyright 2004 Juan Lang
19 *
20 * This library is free software; you can redistribute it and/or
21 * modify it under the terms of the GNU Lesser General Public
22 * License as published by the Free Software Foundation; either
23 * version 2.1 of the License, or (at your option) any later version.
24 *
25 * This library is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
28 * Lesser General Public License for more details.
29 *
30 * You should have received a copy of the GNU Lesser General Public
31 * License along with this library; if not, write to the Free Software
32 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
33 *
34 * TODO
35 * Use the file flag hints O_SEQUENTIAL, O_RANDOM, O_SHORT_LIVED
36 */
37
38 #include <precomp.h>
39 #include "wine/unicode.h"
40
41 #include <sys/utime.h>
42 #include <direct.h>
43 int *__p__fmode(void);
44 int *__p___mb_cur_max(void);
45
46 #ifdef feof
47 #undef feof
48 #endif
49 #ifdef _fileno
50 #undef _fileno
51 #endif
52 #ifdef ferror
53 #undef ferror
54 #endif
55 #ifdef clearerr
56 #undef clearerr
57 #endif
58
59 #undef getc
60 #undef getwc
61 #undef getchar
62 #undef getwchar
63 #undef putc
64 #undef putwc
65 #undef putchar
66 #undef putwchar
67
68 #undef vprintf
69 #undef vwprintf
70
71 /* for stat mode, permissions apply to all,owner and group */
72 #define ALL_S_IREAD (_S_IREAD | (_S_IREAD >> 3) | (_S_IREAD >> 6))
73 #define ALL_S_IWRITE (_S_IWRITE | (_S_IWRITE >> 3) | (_S_IWRITE >> 6))
74 #define ALL_S_IEXEC (_S_IEXEC | (_S_IEXEC >> 3) | (_S_IEXEC >> 6))
75
76 /* _access() bit flags FIXME: incomplete */
77 /* defined in crt/io.h */
78
79 /* values for wxflag in file descriptor */
80 #define WX_OPEN 0x01
81 #define WX_ATEOF 0x02
82 #define WX_READEOF 0x04 /* like ATEOF, but for underlying file rather than buffer */
83 #define WX_DONTINHERIT 0x10
84 #define WX_APPEND 0x20
85 #define WX_TEXT 0x80
86
87 /* FIXME: this should be allocated dynamically */
88 #define MAX_FILES 2048
89
90 /* ReactOS: Use _FDINFO instead! */
91 typedef struct {
92 HANDLE handle;
93 unsigned char wxflag;
94 DWORD unkn[7]; /* critical section and init flag */
95 } ioinfo;
96
97 /*static */ioinfo fdesc[MAX_FILES];
98
99 FILE _iob[3];
100
101 static int fdstart = 3; /* first unallocated fd */
102 static int fdend = 3; /* highest allocated fd */
103
104 static FILE* fstreams[2048];
105 static int stream_idx;
106
107 /* INTERNAL: process umask */
108 static int MSVCRT_umask = 0;
109
110 /* INTERNAL: Static buffer for temp file name */
111 static char tmpname[MAX_PATH];
112
113 static const unsigned int EXE = 'e' << 16 | 'x' << 8 | 'e';
114 static const unsigned int BAT = 'b' << 16 | 'a' << 8 | 't';
115 static const unsigned int CMD = 'c' << 16 | 'm' << 8 | 'd';
116 static const unsigned int COM = 'c' << 16 | 'o' << 8 | 'm';
117
118 #define TOUL(x) (ULONGLONG)(x)
119 static const ULONGLONG WCEXE = TOUL('e') << 32 | TOUL('x') << 16 | TOUL('e');
120 static const ULONGLONG WCBAT = TOUL('b') << 32 | TOUL('a') << 16 | TOUL('t');
121 static const ULONGLONG WCCMD = TOUL('c') << 32 | TOUL('m') << 16 | TOUL('d');
122 static const ULONGLONG WCCOM = TOUL('c') << 32 | TOUL('o') << 16 | TOUL('m');
123
124 /* This critical section protects the tables fdesc and fstreams,
125 * and their related indexes, fdstart, fdend,
126 * and stream_idx, from race conditions.
127 * It doesn't protect against race conditions manipulating the underlying files
128 * or flags; doing so would probably be better accomplished with per-file
129 * protection, rather than locking the whole table for every change.
130 */
131 static CRITICAL_SECTION FILE_cs;
132 #define LOCK_FILES() do { EnterCriticalSection(&FILE_cs); } while (0)
133 #define UNLOCK_FILES() do { LeaveCriticalSection(&FILE_cs); } while (0)
134
135 static void stat64_to_stat(const struct __stat64 *buf64, struct _stat *buf)
136 {
137 buf->st_dev = buf64->st_dev;
138 buf->st_ino = buf64->st_ino;
139 buf->st_mode = buf64->st_mode;
140 buf->st_nlink = buf64->st_nlink;
141 buf->st_uid = buf64->st_uid;
142 buf->st_gid = buf64->st_gid;
143 buf->st_rdev = buf64->st_rdev;
144 buf->st_size = buf64->st_size;
145 buf->st_atime = buf64->st_atime;
146 buf->st_mtime = buf64->st_mtime;
147 buf->st_ctime = buf64->st_ctime;
148 }
149
150 static void stat64_to_stati64(const struct __stat64 *buf64, struct _stati64 *buf)
151 {
152 buf->st_dev = buf64->st_dev;
153 buf->st_ino = buf64->st_ino;
154 buf->st_mode = buf64->st_mode;
155 buf->st_nlink = buf64->st_nlink;
156 buf->st_uid = buf64->st_uid;
157 buf->st_gid = buf64->st_gid;
158 buf->st_rdev = buf64->st_rdev;
159 buf->st_size = buf64->st_size;
160 buf->st_atime = buf64->st_atime;
161 buf->st_mtime = buf64->st_mtime;
162 buf->st_ctime = buf64->st_ctime;
163 }
164
165 static inline BOOL is_valid_fd(int fd)
166 {
167 return fd >= 0 && fd < fdend && (fdesc[fd].wxflag & WX_OPEN);
168 }
169
170 /* INTERNAL: Get the HANDLE for a fd
171 * This doesn't lock the table, because a failure will result in
172 * INVALID_HANDLE_VALUE being returned, which should be handled correctly. If
173 * it returns a valid handle which is about to be closed, a subsequent call
174 * will fail, most likely in a sane way.
175 */
176 static HANDLE fdtoh(int fd)
177 {
178 if (!is_valid_fd(fd))
179 {
180 WARN(":fd (%d) - no handle!\n",fd);
181 *__doserrno() = 0;
182 *_errno() = EBADF;
183 return INVALID_HANDLE_VALUE;
184 }
185 if (fdesc[fd].handle == INVALID_HANDLE_VALUE) FIXME("wtf\n");
186 return fdesc[fd].handle;
187 }
188
189 /* INTERNAL: free a file entry fd */
190 static void free_fd(int fd)
191 {
192 LOCK_FILES();
193 fdesc[fd].handle = INVALID_HANDLE_VALUE;
194 fdesc[fd].wxflag = 0;
195 TRACE(":fd (%d) freed\n",fd);
196 if (fd < 3) /* don't use 0,1,2 for user files */
197 {
198 switch (fd)
199 {
200 case 0: SetStdHandle(STD_INPUT_HANDLE, NULL); break;
201 case 1: SetStdHandle(STD_OUTPUT_HANDLE, NULL); break;
202 case 2: SetStdHandle(STD_ERROR_HANDLE, NULL); break;
203 }
204 }
205 else
206 {
207 if (fd == fdend - 1)
208 fdend--;
209 if (fd < fdstart)
210 fdstart = fd;
211 }
212 UNLOCK_FILES();
213 }
214
215 /* INTERNAL: Allocate an fd slot from a Win32 HANDLE, starting from fd */
216 /* caller must hold the files lock */
217 static int alloc_fd_from(HANDLE hand, int flag, int fd)
218 {
219 if (fd >= MAX_FILES)
220 {
221 WARN(":files exhausted!\n");
222 return -1;
223 }
224 fdesc[fd].handle = hand;
225 fdesc[fd].wxflag = WX_OPEN | (flag & (WX_DONTINHERIT | WX_APPEND | WX_TEXT));
226
227 /* locate next free slot */
228 if (fd == fdstart && fd == fdend)
229 fdstart = fdend + 1;
230 else
231 while (fdstart < fdend &&
232 fdesc[fdstart].handle != INVALID_HANDLE_VALUE)
233 fdstart++;
234 /* update last fd in use */
235 if (fd >= fdend)
236 fdend = fd + 1;
237 TRACE("fdstart is %d, fdend is %d\n", fdstart, fdend);
238
239 switch (fd)
240 {
241 case 0: SetStdHandle(STD_INPUT_HANDLE, hand); break;
242 case 1: SetStdHandle(STD_OUTPUT_HANDLE, hand); break;
243 case 2: SetStdHandle(STD_ERROR_HANDLE, hand); break;
244 }
245
246 return fd;
247 }
248
249 /* INTERNAL: Allocate an fd slot from a Win32 HANDLE */
250 /*static */int alloc_fd(HANDLE hand, int flag)
251 {
252 int ret;
253
254 LOCK_FILES();
255 TRACE(":handle (%p) allocating fd (%d)\n",hand,fdstart);
256 ret = alloc_fd_from(hand, flag, fdstart);
257 UNLOCK_FILES();
258 return ret;
259 }
260
261 /* INTERNAL: Allocate a FILE* for an fd slot */
262 /* caller must hold the files lock */
263 static FILE* alloc_fp(void)
264 {
265 unsigned int i;
266
267 for (i = 3; i < sizeof(fstreams) / sizeof(fstreams[0]); i++)
268 {
269 if (!fstreams[i] || fstreams[i]->_flag == 0)
270 {
271 if (!fstreams[i])
272 {
273 if (!(fstreams[i] = calloc(sizeof(FILE),1)))
274 return NULL;
275 if (i == stream_idx) stream_idx++;
276 }
277 return fstreams[i];
278 }
279 }
280 return NULL;
281 }
282
283 /* INTERNAL: initialize a FILE* from an open fd */
284 static int init_fp(FILE* file, int fd, unsigned stream_flags)
285 {
286 TRACE(":fd (%d) allocating FILE*\n",fd);
287 if (!is_valid_fd(fd))
288 {
289 WARN(":invalid fd %d\n",fd);
290 *__doserrno() = 0;
291 *_errno() = EBADF;
292 return -1;
293 }
294 memset(file, 0, sizeof(*file));
295 file->_file = fd;
296 file->_flag = stream_flags;
297
298 TRACE(":got FILE* (%p)\n",file);
299 return 0;
300 }
301
302 /* INTERNAL: Create an inheritance data block (for spawned process)
303 * The inheritance block is made of:
304 * 00 int nb of file descriptor (NBFD)
305 * 04 char file flags (wxflag): repeated for each fd
306 * 4+NBFD HANDLE file handle: repeated for each fd
307 */
308 unsigned create_io_inherit_block(WORD *size, BYTE **block)
309 {
310 int fd;
311 char* wxflag_ptr;
312 HANDLE* handle_ptr;
313
314 *size = sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * fdend;
315 *block = calloc(*size, 1);
316 if (!*block)
317 {
318 *size = 0;
319 return FALSE;
320 }
321 wxflag_ptr = (char*)*block + sizeof(unsigned);
322 handle_ptr = (HANDLE*)(wxflag_ptr + fdend * sizeof(char));
323
324 *(unsigned*)*block = fdend;
325 for (fd = 0; fd < fdend; fd++)
326 {
327 /* to be inherited, we need it to be open, and that DONTINHERIT isn't set */
328 if ((fdesc[fd].wxflag & (WX_OPEN | WX_DONTINHERIT)) == WX_OPEN)
329 {
330 *wxflag_ptr = fdesc[fd].wxflag;
331 *handle_ptr = fdesc[fd].handle;
332 }
333 else
334 {
335 *wxflag_ptr = 0;
336 *handle_ptr = INVALID_HANDLE_VALUE;
337 }
338 wxflag_ptr++; handle_ptr++;
339 }
340 return TRUE;
341 }
342
343 /* INTERNAL: Set up all file descriptors,
344 * as well as default streams (stdin, stderr and stdout)
345 */
346 void msvcrt_init_io(void)
347 {
348 STARTUPINFOA si;
349 int i;
350
351 InitializeCriticalSection(&FILE_cs);
352 FILE_cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": FILE_cs");
353 GetStartupInfoA(&si);
354 if (si.cbReserved2 != 0 && si.lpReserved2 != NULL)
355 {
356 char* wxflag_ptr;
357 HANDLE* handle_ptr;
358
359 fdend = *(unsigned*)si.lpReserved2;
360
361 wxflag_ptr = (char*)(si.lpReserved2 + sizeof(unsigned));
362 handle_ptr = (HANDLE*)(wxflag_ptr + fdend * sizeof(char));
363
364 fdend = min(fdend, sizeof(fdesc) / sizeof(fdesc[0]));
365 for (i = 0; i < fdend; i++)
366 {
367 if ((*wxflag_ptr & WX_OPEN) && *handle_ptr != INVALID_HANDLE_VALUE)
368 {
369 fdesc[i].wxflag = *wxflag_ptr;
370 fdesc[i].handle = *handle_ptr;
371 }
372 else
373 {
374 fdesc[i].wxflag = 0;
375 fdesc[i].handle = INVALID_HANDLE_VALUE;
376 }
377 wxflag_ptr++; handle_ptr++;
378 }
379 for (fdstart = 3; fdstart < fdend; fdstart++)
380 if (fdesc[fdstart].handle == INVALID_HANDLE_VALUE) break;
381 }
382
383 if (!(fdesc[0].wxflag & WX_OPEN) || fdesc[0].handle == INVALID_HANDLE_VALUE)
384 {
385 #ifndef __REACTOS__
386 DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_INPUT_HANDLE),
387 GetCurrentProcess(), &fdesc[0].handle, 0, TRUE,
388 DUPLICATE_SAME_ACCESS);
389 #else
390 fdesc[0].handle = GetStdHandle(STD_INPUT_HANDLE);
391 if (fdesc[0].handle == NULL)
392 fdesc[0].handle = INVALID_HANDLE_VALUE;
393 #endif
394 fdesc[0].wxflag = WX_OPEN | WX_TEXT;
395 }
396 if (!(fdesc[1].wxflag & WX_OPEN) || fdesc[1].handle == INVALID_HANDLE_VALUE)
397 {
398 #ifndef __REACTOS__
399 DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_OUTPUT_HANDLE),
400 GetCurrentProcess(), &fdesc[1].handle, 0, TRUE,
401 DUPLICATE_SAME_ACCESS);
402 #else
403 fdesc[1].handle = GetStdHandle(STD_OUTPUT_HANDLE);
404 if (fdesc[1].handle == NULL)
405 fdesc[1].handle = INVALID_HANDLE_VALUE;
406 #endif
407 fdesc[1].wxflag = WX_OPEN | WX_TEXT;
408 }
409 if (!(fdesc[2].wxflag & WX_OPEN) || fdesc[2].handle == INVALID_HANDLE_VALUE)
410 {
411 #ifndef __REACTOS__
412 DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_ERROR_HANDLE),
413 GetCurrentProcess(), &fdesc[2].handle, 0, TRUE,
414 DUPLICATE_SAME_ACCESS);
415 #else
416 fdesc[2].handle = GetStdHandle(STD_ERROR_HANDLE);
417 if (fdesc[2].handle == NULL)
418 fdesc[2].handle = INVALID_HANDLE_VALUE;
419 #endif
420 fdesc[2].wxflag = WX_OPEN | WX_TEXT;
421 }
422
423 TRACE(":handles (%p)(%p)(%p)\n",fdesc[0].handle,
424 fdesc[1].handle,fdesc[2].handle);
425
426 memset(_iob,0,3*sizeof(FILE));
427 for (i = 0; i < 3; i++)
428 {
429 /* FILE structs for stdin/out/err are static and never deleted */
430 fstreams[i] = &_iob[i];
431 _iob[i]._file = i;
432 _iob[i]._tmpfname = NULL;
433 _iob[i]._flag = (i == 0) ? _IOREAD : _IOWRT;
434 }
435 stream_idx = 3;
436 }
437
438 /* INTERNAL: Flush stdio file buffer */
439 static int flush_buffer(FILE* file)
440 {
441 if(file->_bufsiz) {
442 int cnt=file->_ptr-file->_base;
443 if(cnt>0 && _write(file->_file, file->_base, cnt) != cnt) {
444 file->_flag |= _IOERR;
445 return EOF;
446 }
447 file->_ptr=file->_base;
448 file->_cnt=file->_bufsiz;
449 }
450 return 0;
451 }
452
453 /* INTERNAL: Allocate stdio file buffer */
454 static void alloc_buffer(FILE* file)
455 {
456 file->_base = calloc(BUFSIZ,1);
457 if(file->_base) {
458 file->_bufsiz = BUFSIZ;
459 file->_flag |= _IOMYBUF;
460 } else {
461 file->_base = (char*)(&file->_charbuf);
462 /* put here 2 ??? */
463 file->_bufsiz = sizeof(file->_charbuf);
464 }
465 file->_ptr = file->_base;
466 file->_cnt = 0;
467 }
468
469 /* INTERNAL: Convert integer to base32 string (0-9a-v), 0 becomes "" */
470 static void int_to_base32(int num, char *str)
471 {
472 char *p;
473 int n = num;
474 int digits = 0;
475
476 while (n != 0)
477 {
478 n >>= 5;
479 digits++;
480 }
481 p = str + digits;
482 *p = 0;
483 while (--p >= str)
484 {
485 *p = (num & 31) + '0';
486 if (*p > '9')
487 *p += ('a' - '0' - 10);
488 num >>= 5;
489 }
490 }
491
492 /*********************************************************************
493 * __p__iob(MSVCRT.@)
494 */
495 FILE * CDECL __p__iob(void)
496 {
497 return &_iob[0];
498 }
499
500 /*********************************************************************
501 * _access (MSVCRT.@)
502 */
503 int CDECL _access(const char *filename, int mode)
504 {
505 DWORD attr = GetFileAttributesA(filename);
506
507 TRACE("(%s,%d) %d\n",filename,mode,attr);
508
509 if (!filename || attr == INVALID_FILE_ATTRIBUTES)
510 {
511 __set_errno(GetLastError());
512 return -1;
513 }
514 if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & W_OK))
515 {
516 __set_errno(ERROR_ACCESS_DENIED);
517 return -1;
518 }
519 return 0;
520 }
521
522 /*********************************************************************
523 * _waccess (MSVCRT.@)
524 */
525 int CDECL _waccess(const wchar_t *filename, int mode)
526 {
527 DWORD attr = GetFileAttributesW(filename);
528
529 TRACE("(%s,%d) %d\n",debugstr_w(filename),mode,attr);
530
531 if (!filename || attr == INVALID_FILE_ATTRIBUTES)
532 {
533 __set_errno(GetLastError());
534 return -1;
535 }
536 if ((attr & FILE_ATTRIBUTE_READONLY) && (mode & W_OK))
537 {
538 __set_errno(ERROR_ACCESS_DENIED);
539 return -1;
540 }
541 return 0;
542 }
543
544 /*********************************************************************
545 * _chmod (MSVCRT.@)
546 */
547 int CDECL _chmod(const char *path, int flags)
548 {
549 DWORD oldFlags = GetFileAttributesA(path);
550
551 if (oldFlags != INVALID_FILE_ATTRIBUTES)
552 {
553 DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
554 oldFlags | FILE_ATTRIBUTE_READONLY;
555
556 if (newFlags == oldFlags || SetFileAttributesA(path, newFlags))
557 return 0;
558 }
559 __set_errno(GetLastError());
560 return -1;
561 }
562
563 /*********************************************************************
564 * _wchmod (MSVCRT.@)
565 */
566 int CDECL _wchmod(const wchar_t *path, int flags)
567 {
568 DWORD oldFlags = GetFileAttributesW(path);
569
570 if (oldFlags != INVALID_FILE_ATTRIBUTES)
571 {
572 DWORD newFlags = (flags & _S_IWRITE)? oldFlags & ~FILE_ATTRIBUTE_READONLY:
573 oldFlags | FILE_ATTRIBUTE_READONLY;
574
575 if (newFlags == oldFlags || SetFileAttributesW(path, newFlags))
576 return 0;
577 }
578 __set_errno(GetLastError());
579 return -1;
580 }
581
582 /*********************************************************************
583 * _unlink (MSVCRT.@)
584 */
585 int CDECL _unlink(const char *path)
586 {
587 TRACE("%s\n",debugstr_a(path));
588 if(DeleteFileA(path))
589 return 0;
590 TRACE("failed (%d)\n",GetLastError());
591 __set_errno(GetLastError());
592 return -1;
593 }
594
595 /*********************************************************************
596 * _wunlink (MSVCRT.@)
597 */
598 int CDECL _wunlink(const wchar_t *path)
599 {
600 TRACE("(%s)\n",debugstr_w(path));
601 if(DeleteFileW(path))
602 return 0;
603 TRACE("failed (%d)\n",GetLastError());
604 __set_errno(GetLastError());
605 return -1;
606 }
607
608 /* _flushall calls fflush which calls _flushall */
609 int CDECL fflush(FILE* file);
610
611 /*********************************************************************
612 * _flushall (MSVCRT.@)
613 */
614 int CDECL _flushall(void)
615 {
616 int i, num_flushed = 0;
617
618 LOCK_FILES();
619 for (i = 3; i < stream_idx; i++)
620 if (fstreams[i] && fstreams[i]->_flag)
621 {
622 #if 0
623 /* FIXME: flush, do not commit */
624 if (_commit(i) == -1)
625 if (fstreams[i])
626 fstreams[i]->_flag |= _IOERR;
627 #endif
628 if(fstreams[i]->_flag & _IOWRT) {
629 fflush(fstreams[i]);
630 num_flushed++;
631 }
632 }
633 UNLOCK_FILES();
634
635 TRACE(":flushed (%d) handles\n",num_flushed);
636 return num_flushed;
637 }
638
639 /*********************************************************************
640 * fflush (MSVCRT.@)
641 */
642 int CDECL fflush(FILE* file)
643 {
644 if(!file) {
645 _flushall();
646 } else if(file->_flag & _IOWRT) {
647 int res=flush_buffer(file);
648 return res;
649 }
650 return 0;
651 }
652
653 /*********************************************************************
654 * _close (MSVCRT.@)
655 */
656 int CDECL _close(int fd)
657 {
658 HANDLE hand;
659 int ret;
660
661 LOCK_FILES();
662 hand = fdtoh(fd);
663 TRACE(":fd (%d) handle (%p)\n",fd,hand);
664 if (hand == INVALID_HANDLE_VALUE)
665 ret = -1;
666 else if (!CloseHandle(hand))
667 {
668 WARN(":failed-last error (%d)\n",GetLastError());
669 __set_errno(GetLastError());
670 ret = -1;
671 }
672 else
673 {
674 free_fd(fd);
675 ret = 0;
676 }
677 UNLOCK_FILES();
678 TRACE(":ok\n");
679 return ret;
680 }
681
682 /*********************************************************************
683 * _commit (MSVCRT.@)
684 */
685 int CDECL _commit(int fd)
686 {
687 HANDLE hand = fdtoh(fd);
688
689 TRACE(":fd (%d) handle (%p)\n",fd,hand);
690 if (hand == INVALID_HANDLE_VALUE)
691 return -1;
692
693 if (!FlushFileBuffers(hand))
694 {
695 if (GetLastError() == ERROR_INVALID_HANDLE)
696 {
697 /* FlushFileBuffers fails for console handles
698 * so we ignore this error.
699 */
700 return 0;
701 }
702 TRACE(":failed-last error (%d)\n",GetLastError());
703 __set_errno(GetLastError());
704 return -1;
705 }
706 TRACE(":ok\n");
707 return 0;
708 }
709
710 /*********************************************************************
711 * _dup2 (MSVCRT.@)
712 * NOTES
713 * MSDN isn't clear on this point, but the remarks for _pipe
714 * indicate file descriptors duplicated with _dup and _dup2 are always
715 * inheritable.
716 */
717 int CDECL _dup2(int od, int nd)
718 {
719 int ret;
720
721 TRACE("(od=%d, nd=%d)\n", od, nd);
722 LOCK_FILES();
723 if (nd < MAX_FILES && is_valid_fd(od))
724 {
725 HANDLE handle;
726
727 if (DuplicateHandle(GetCurrentProcess(), fdesc[od].handle,
728 GetCurrentProcess(), &handle, 0, TRUE, DUPLICATE_SAME_ACCESS))
729 {
730 int wxflag = fdesc[od].wxflag & ~_O_NOINHERIT;
731
732 if (is_valid_fd(nd))
733 _close(nd);
734 ret = alloc_fd_from(handle, wxflag, nd);
735 if (ret == -1)
736 {
737 CloseHandle(handle);
738 *_errno() = EMFILE;
739 }
740 else
741 {
742 /* _dup2 returns 0, not nd, on success */
743 ret = 0;
744 }
745 }
746 else
747 {
748 ret = -1;
749 __set_errno(GetLastError());
750 }
751 }
752 else
753 {
754 *_errno() = EBADF;
755 ret = -1;
756 }
757 UNLOCK_FILES();
758 return ret;
759 }
760
761 /*********************************************************************
762 * _dup (MSVCRT.@)
763 */
764 int CDECL _dup(int od)
765 {
766 int fd, ret;
767
768 LOCK_FILES();
769 fd = fdstart;
770 if (_dup2(od, fd) == 0)
771 ret = fd;
772 else
773 ret = -1;
774 UNLOCK_FILES();
775 return ret;
776 }
777
778 /*********************************************************************
779 * _eof (MSVCRT.@)
780 */
781 int CDECL _eof(int fd)
782 {
783 DWORD curpos,endpos;
784 LONG hcurpos,hendpos;
785 HANDLE hand = fdtoh(fd);
786
787 TRACE(":fd (%d) handle (%p)\n",fd,hand);
788
789 if (hand == INVALID_HANDLE_VALUE)
790 return -1;
791
792 if (fdesc[fd].wxflag & WX_ATEOF) return TRUE;
793
794 /* Otherwise we do it the hard way */
795 hcurpos = hendpos = 0;
796 curpos = SetFilePointer(hand, 0, &hcurpos, FILE_CURRENT);
797 endpos = SetFilePointer(hand, 0, &hendpos, FILE_END);
798
799 if (curpos == endpos && hcurpos == hendpos)
800 {
801 /* FIXME: shouldn't WX_ATEOF be set here? */
802 return TRUE;
803 }
804
805 SetFilePointer(hand, curpos, &hcurpos, FILE_BEGIN);
806 return FALSE;
807 }
808
809 /*********************************************************************
810 * _fcloseall (MSVCRT.@)
811 */
812 int CDECL _fcloseall(void)
813 {
814 int num_closed = 0, i;
815
816 LOCK_FILES();
817 for (i = 3; i < stream_idx; i++)
818 if (fstreams[i] && fstreams[i]->_flag &&
819 !fclose(fstreams[i]))
820 num_closed++;
821 UNLOCK_FILES();
822
823 TRACE(":closed (%d) handles\n",num_closed);
824 return num_closed;
825 }
826
827 /* free everything on process exit */
828 void msvcrt_free_io(void)
829 {
830 _fcloseall();
831 /* The Win32 _fcloseall() function explicitly doesn't close stdin,
832 * stdout, and stderr (unlike GNU), so we need to fclose() them here
833 * or they won't get flushed.
834 */
835 fclose(&_iob[0]);
836 fclose(&_iob[1]);
837 fclose(&_iob[2]);
838 FILE_cs.DebugInfo->Spare[0] = 0;
839 DeleteCriticalSection(&FILE_cs);
840 }
841
842 /*********************************************************************
843 * _lseeki64 (MSVCRT.@)
844 */
845 __int64 CDECL _lseeki64(int fd, __int64 offset, int whence)
846 {
847 HANDLE hand = fdtoh(fd);
848 LARGE_INTEGER ofs, ret;
849
850 TRACE(":fd (%d) handle (%p)\n",fd,hand);
851 if (hand == INVALID_HANDLE_VALUE)
852 return -1;
853
854 if (whence < 0 || whence > 2)
855 {
856 *_errno() = EINVAL;
857 return -1;
858 }
859
860 TRACE(":fd (%d) to %s pos %s\n",
861 fd,wine_dbgstr_longlong(offset),
862 (whence==SEEK_SET)?"SEEK_SET":
863 (whence==SEEK_CUR)?"SEEK_CUR":
864 (whence==SEEK_END)?"SEEK_END":"UNKNOWN");
865
866 ofs.QuadPart = offset;
867 if (SetFilePointerEx(hand, ofs, &ret, whence))
868 {
869 fdesc[fd].wxflag &= ~(WX_ATEOF|WX_READEOF);
870 /* FIXME: What if we seek _to_ EOF - is EOF set? */
871
872 return ret.QuadPart;
873 }
874 TRACE(":error-last error (%d)\n",GetLastError());
875 __set_errno(GetLastError());
876 return -1;
877 }
878
879 /*********************************************************************
880 * _lseek (MSVCRT.@)
881 */
882 LONG CDECL _lseek(int fd, LONG offset, int whence)
883 {
884 return _lseeki64(fd, offset, whence);
885 }
886
887 /*********************************************************************
888 * _locking (MSVCRT.@)
889 *
890 * This is untested; the underlying LockFile doesn't work yet.
891 */
892 int CDECL _locking(int fd, int mode, LONG nbytes)
893 {
894 BOOL ret;
895 DWORD cur_locn;
896 HANDLE hand = fdtoh(fd);
897
898 TRACE(":fd (%d) handle (%p)\n",fd,hand);
899 if (hand == INVALID_HANDLE_VALUE)
900 return -1;
901
902 if (mode < 0 || mode > 4)
903 {
904 *_errno() = EINVAL;
905 return -1;
906 }
907
908 TRACE(":fd (%d) by 0x%08x mode %s\n",
909 fd,nbytes,(mode==_LK_UNLCK)?"_LK_UNLCK":
910 (mode==_LK_LOCK)?"_LK_LOCK":
911 (mode==_LK_NBLCK)?"_LK_NBLCK":
912 (mode==_LK_RLCK)?"_LK_RLCK":
913 (mode==_LK_NBRLCK)?"_LK_NBRLCK":
914 "UNKNOWN");
915
916 if ((cur_locn = SetFilePointer(hand, 0L, NULL, SEEK_CUR)) == INVALID_SET_FILE_POINTER)
917 {
918 FIXME ("Seek failed\n");
919 *_errno() = EINVAL; /* FIXME */
920 return -1;
921 }
922 if (mode == _LK_LOCK || mode == _LK_RLCK)
923 {
924 int nretry = 10;
925 ret = 1; /* just to satisfy gcc */
926 while (nretry--)
927 {
928 ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
929 if (ret) break;
930 Sleep(1);
931 }
932 }
933 else if (mode == _LK_UNLCK)
934 ret = UnlockFile(hand, cur_locn, 0L, nbytes, 0L);
935 else
936 ret = LockFile(hand, cur_locn, 0L, nbytes, 0L);
937 /* FIXME - what about error settings? */
938 return ret ? 0 : -1;
939 }
940
941 /*********************************************************************
942 * fseek (MSVCRT.@)
943 */
944 int CDECL fseek(FILE* file, long offset, int whence)
945 {
946 /* Flush output if needed */
947 if(file->_flag & _IOWRT)
948 flush_buffer(file);
949
950 if(whence == SEEK_CUR && file->_flag & _IOREAD ) {
951 offset -= file->_cnt;
952 }
953 /* Discard buffered input */
954 file->_cnt = 0;
955 file->_ptr = file->_base;
956 /* Reset direction of i/o */
957 if(file->_flag & _IORW) {
958 file->_flag &= ~(_IOREAD|_IOWRT);
959 }
960 /* Clear end of file flag */
961 file->_flag &= ~_IOEOF;
962 return (_lseek(file->_file,offset,whence) == -1)?-1:0;
963 }
964
965 /*********************************************************************
966 * _chsize (MSVCRT.@)
967 */
968 int CDECL _chsize(int fd, long size)
969 {
970 LONG cur, pos;
971 HANDLE handle;
972 BOOL ret = FALSE;
973
974 TRACE("(fd=%d, size=%ld)\n", fd, size);
975
976 LOCK_FILES();
977
978 handle = fdtoh(fd);
979 if (handle != INVALID_HANDLE_VALUE)
980 {
981 /* save the current file pointer */
982 cur = _lseek(fd, 0, SEEK_CUR);
983 if (cur >= 0)
984 {
985 pos = _lseek(fd, size, SEEK_SET);
986 if (pos >= 0)
987 {
988 ret = SetEndOfFile(handle);
989 if (!ret) __set_errno(GetLastError());
990 }
991
992 /* restore the file pointer */
993 _lseek(fd, cur, SEEK_SET);
994 }
995 }
996
997 UNLOCK_FILES();
998 return ret ? 0 : -1;
999 }
1000
1001 /*********************************************************************
1002 * clearerr (MSVCRT.@)
1003 */
1004 void CDECL clearerr(FILE* file)
1005 {
1006 TRACE(":file (%p) fd (%d)\n",file,file->_file);
1007 file->_flag &= ~(_IOERR | _IOEOF);
1008 }
1009
1010 /*********************************************************************
1011 * rewind (MSVCRT.@)
1012 */
1013 void CDECL rewind(FILE* file)
1014 {
1015 TRACE(":file (%p) fd (%d)\n",file,file->_file);
1016 fseek(file, 0L, SEEK_SET);
1017 clearerr(file);
1018 }
1019
1020 static int get_flags(const char* mode, int *open_flags, int* stream_flags)
1021 {
1022 int plus = strchr(mode, '+') != NULL;
1023
1024 switch(*mode++)
1025 {
1026 case 'R': case 'r':
1027 *open_flags = plus ? _O_RDWR : _O_RDONLY;
1028 *stream_flags = plus ? _IORW : _IOREAD;
1029 break;
1030 case 'W': case 'w':
1031 *open_flags = _O_CREAT | _O_TRUNC | (plus ? _O_RDWR : _O_WRONLY);
1032 *stream_flags = plus ? _IORW : _IOWRT;
1033 break;
1034 case 'A': case 'a':
1035 *open_flags = _O_CREAT | _O_APPEND | (plus ? _O_RDWR : _O_WRONLY);
1036 *stream_flags = plus ? _IORW : _IOWRT;
1037 break;
1038 default:
1039 return -1;
1040 }
1041
1042 while (*mode)
1043 switch (*mode++)
1044 {
1045 case 'B': case 'b':
1046 *open_flags |= _O_BINARY;
1047 *open_flags &= ~_O_TEXT;
1048 break;
1049 case 'T': case 't':
1050 *open_flags |= _O_TEXT;
1051 *open_flags &= ~_O_BINARY;
1052 break;
1053 case '+':
1054 break;
1055 default:
1056 FIXME(":unknown flag %c not supported\n",mode[-1]);
1057 }
1058 return 0;
1059 }
1060
1061 /*********************************************************************
1062 * _fdopen (MSVCRT.@)
1063 */
1064 FILE* CDECL _fdopen(int fd, const char *mode)
1065 {
1066 int open_flags, stream_flags;
1067 FILE* file;
1068
1069 if (get_flags(mode, &open_flags, &stream_flags) == -1) return NULL;
1070
1071 LOCK_FILES();
1072 if (!(file = alloc_fp()))
1073 file = NULL;
1074 else if (init_fp(file, fd, stream_flags) == -1)
1075 {
1076 file->_flag = 0;
1077 file = NULL;
1078 }
1079 else TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,mode,file);
1080 UNLOCK_FILES();
1081
1082 return file;
1083 }
1084
1085 /*********************************************************************
1086 * _wfdopen (MSVCRT.@)
1087 */
1088 FILE* CDECL _wfdopen(int fd, const wchar_t *mode)
1089 {
1090 unsigned mlen = strlenW(mode);
1091 char *modea = calloc(mlen + 1, 1);
1092 FILE* file = NULL;
1093 int open_flags, stream_flags;
1094
1095 if (modea &&
1096 WideCharToMultiByte(CP_ACP,0,mode,mlen,modea,mlen,NULL,NULL))
1097 {
1098 if (get_flags(modea, &open_flags, &stream_flags) == -1) return NULL;
1099 LOCK_FILES();
1100 if (!(file = alloc_fp()))
1101 file = NULL;
1102 else if (init_fp(file, fd, stream_flags) == -1)
1103 {
1104 file->_flag = 0;
1105 file = NULL;
1106 }
1107 else
1108 {
1109 if (file)
1110 rewind(file); /* FIXME: is this needed ??? */
1111 TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,debugstr_w(mode),file);
1112 }
1113 UNLOCK_FILES();
1114 }
1115 return file;
1116 }
1117
1118 /*********************************************************************
1119 * _filelength (MSVCRT.@)
1120 */
1121 LONG CDECL _filelength(int fd)
1122 {
1123 LONG curPos = _lseek(fd, 0, SEEK_CUR);
1124 if (curPos != -1)
1125 {
1126 LONG endPos = _lseek(fd, 0, SEEK_END);
1127 if (endPos != -1)
1128 {
1129 if (endPos != curPos)
1130 _lseek(fd, curPos, SEEK_SET);
1131 return endPos;
1132 }
1133 }
1134 return -1;
1135 }
1136
1137 /*********************************************************************
1138 * _filelengthi64 (MSVCRT.@)
1139 */
1140 __int64 CDECL _filelengthi64(int fd)
1141 {
1142 __int64 curPos = _lseeki64(fd, 0, SEEK_CUR);
1143 if (curPos != -1)
1144 {
1145 __int64 endPos = _lseeki64(fd, 0, SEEK_END);
1146 if (endPos != -1)
1147 {
1148 if (endPos != curPos)
1149 _lseeki64(fd, curPos, SEEK_SET);
1150 return endPos;
1151 }
1152 }
1153 return -1;
1154 }
1155
1156 /*********************************************************************
1157 * _fileno (MSVCRT.@)
1158 */
1159 int CDECL _fileno(FILE* file)
1160 {
1161 TRACE(":FILE* (%p) fd (%d)\n",file,file->_file);
1162 return file->_file;
1163 }
1164
1165 /*********************************************************************
1166 * _fstat64 (MSVCRT.@)
1167 */
1168 int CDECL _fstat64(int fd, struct __stat64* buf)
1169 {
1170 DWORD dw;
1171 DWORD type;
1172 BY_HANDLE_FILE_INFORMATION hfi;
1173 HANDLE hand = fdtoh(fd);
1174
1175 TRACE(":fd (%d) stat (%p)\n",fd,buf);
1176 if (hand == INVALID_HANDLE_VALUE)
1177 return -1;
1178
1179 if (!buf)
1180 {
1181 WARN(":failed-NULL buf\n");
1182 __set_errno(ERROR_INVALID_PARAMETER);
1183 return -1;
1184 }
1185
1186 memset(&hfi, 0, sizeof(hfi));
1187 memset(buf, 0, sizeof(struct __stat64));
1188 type = GetFileType(hand);
1189 if (type == FILE_TYPE_PIPE)
1190 {
1191 buf->st_dev = buf->st_rdev = fd;
1192 buf->st_mode = S_IFIFO;
1193 buf->st_nlink = 1;
1194 }
1195 else if (type == FILE_TYPE_CHAR)
1196 {
1197 buf->st_dev = buf->st_rdev = fd;
1198 buf->st_mode = S_IFCHR;
1199 buf->st_nlink = 1;
1200 }
1201 else /* FILE_TYPE_DISK etc. */
1202 {
1203 if (!GetFileInformationByHandle(hand, &hfi))
1204 {
1205 WARN(":failed-last error (%d)\n",GetLastError());
1206 __set_errno(ERROR_INVALID_PARAMETER);
1207 return -1;
1208 }
1209 buf->st_mode = S_IFREG | S_IREAD;
1210 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1211 buf->st_mode |= S_IWRITE;
1212 buf->st_size = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
1213 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
1214 buf->st_atime = dw;
1215 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
1216 buf->st_mtime = buf->st_ctime = dw;
1217 buf->st_nlink = hfi.nNumberOfLinks;
1218 }
1219 TRACE(":dwFileAttributes = 0x%x, mode set to 0x%x\n",hfi.dwFileAttributes,
1220 buf->st_mode);
1221 return 0;
1222 }
1223
1224 /*********************************************************************
1225 * _fstati64 (MSVCRT.@)
1226 */
1227 int CDECL _fstati64(int fd, struct _stati64* buf)
1228 {
1229 int ret;
1230 struct __stat64 buf64;
1231
1232 ret = _fstat64(fd, &buf64);
1233 if (!ret)
1234 stat64_to_stati64(&buf64, buf);
1235 return ret;
1236 }
1237
1238 /*********************************************************************
1239 * _fstat (MSVCRT.@)
1240 */
1241 int CDECL _fstat(int fd, struct _stat* buf)
1242 { int ret;
1243 struct __stat64 buf64;
1244
1245 ret = _fstat64(fd, &buf64);
1246 if (!ret)
1247 stat64_to_stat(&buf64, buf);
1248 return ret;
1249 }
1250
1251 /*********************************************************************
1252 * _futime (MSVCRT.@)
1253 */
1254 int CDECL _futime(int fd, struct _utimbuf *t)
1255 {
1256 HANDLE hand = fdtoh(fd);
1257 FILETIME at, wt;
1258
1259 if (!t)
1260 {
1261 time_t currTime;
1262 time(&currTime);
1263 RtlSecondsSince1970ToTime(currTime, (LARGE_INTEGER *)&at);
1264 wt = at;
1265 }
1266 else
1267 {
1268 RtlSecondsSince1970ToTime(t->actime, (LARGE_INTEGER *)&at);
1269 if (t->actime == t->modtime)
1270 wt = at;
1271 else
1272 RtlSecondsSince1970ToTime(t->modtime, (LARGE_INTEGER *)&wt);
1273 }
1274
1275 if (!SetFileTime(hand, NULL, &at, &wt))
1276 {
1277 __set_errno(GetLastError());
1278 return -1 ;
1279 }
1280 return 0;
1281 }
1282
1283 /*********************************************************************
1284 * _get_osfhandle (MSVCRT.@)
1285 */
1286 long CDECL _get_osfhandle(int fd)
1287 {
1288 HANDLE hand = fdtoh(fd);
1289 TRACE(":fd (%d) handle (%p)\n",fd,hand);
1290
1291 return (long)hand;
1292 }
1293
1294 /*********************************************************************
1295 * _isatty (MSVCRT.@)
1296 */
1297 int CDECL _isatty(int fd)
1298 {
1299 HANDLE hand = fdtoh(fd);
1300
1301 TRACE(":fd (%d) handle (%p)\n",fd,hand);
1302 if (hand == INVALID_HANDLE_VALUE)
1303 return 0;
1304
1305 return GetFileType(hand) == FILE_TYPE_CHAR? 1 : 0;
1306 }
1307
1308 /*********************************************************************
1309 * _mktemp (MSVCRT.@)
1310 */
1311 char * CDECL _mktemp(char *pattern)
1312 {
1313 int numX = 0;
1314 char *retVal = pattern;
1315 int id;
1316 char letter = 'a';
1317
1318 while(*pattern)
1319 numX = (*pattern++ == 'X')? numX + 1 : 0;
1320 if (numX < 5)
1321 return NULL;
1322 pattern--;
1323 id = GetCurrentProcessId();
1324 numX = 6;
1325 while(numX--)
1326 {
1327 int tempNum = id / 10;
1328 *pattern-- = id - (tempNum * 10) + '0';
1329 id = tempNum;
1330 }
1331 pattern++;
1332 do
1333 {
1334 *pattern = letter++;
1335 if (GetFileAttributesA(retVal) == INVALID_FILE_ATTRIBUTES &&
1336 GetLastError() == ERROR_FILE_NOT_FOUND)
1337 return retVal;
1338 } while(letter <= 'z');
1339 return NULL;
1340 }
1341
1342 /*********************************************************************
1343 * _wmktemp (MSVCRT.@)
1344 */
1345 wchar_t * CDECL _wmktemp(wchar_t *pattern)
1346 {
1347 int numX = 0;
1348 wchar_t *retVal = pattern;
1349 int id;
1350 wchar_t letter = 'a';
1351
1352 while(*pattern)
1353 numX = (*pattern++ == 'X')? numX + 1 : 0;
1354 if (numX < 5)
1355 return NULL;
1356 pattern--;
1357 id = GetCurrentProcessId();
1358 numX = 6;
1359 while(numX--)
1360 {
1361 int tempNum = id / 10;
1362 *pattern-- = id - (tempNum * 10) + '0';
1363 id = tempNum;
1364 }
1365 pattern++;
1366 do
1367 {
1368 if (GetFileAttributesW(retVal) == INVALID_FILE_ATTRIBUTES &&
1369 GetLastError() == ERROR_FILE_NOT_FOUND)
1370 return retVal;
1371 *pattern = letter++;
1372 } while(letter != '|');
1373 return NULL;
1374 }
1375
1376 /*static */unsigned split_oflags(unsigned oflags)
1377 {
1378 int wxflags = 0;
1379 unsigned unsupp; /* until we support everything */
1380
1381 if (oflags & _O_APPEND) wxflags |= WX_APPEND;
1382 if (oflags & _O_BINARY) {/* Nothing to do */}
1383 else if (oflags & _O_TEXT) wxflags |= WX_TEXT;
1384 else if (*__p__fmode() & _O_BINARY) {/* Nothing to do */}
1385 else wxflags |= WX_TEXT; /* default to TEXT*/
1386 if (oflags & _O_NOINHERIT) wxflags |= WX_DONTINHERIT;
1387
1388 if ((unsupp = oflags & ~(
1389 _O_BINARY|_O_TEXT|_O_APPEND|
1390 _O_TRUNC|_O_EXCL|_O_CREAT|
1391 _O_RDWR|_O_WRONLY|_O_TEMPORARY|
1392 _O_NOINHERIT|
1393 _O_SEQUENTIAL|_O_RANDOM|_O_SHORT_LIVED
1394 )))
1395 ERR(":unsupported oflags 0x%04x\n",unsupp);
1396
1397 return wxflags;
1398 }
1399
1400 /*********************************************************************
1401 * _pipe (MSVCRT.@)
1402 */
1403 int CDECL _pipe(int *pfds, unsigned int psize, int textmode)
1404 {
1405 int ret = -1;
1406 SECURITY_ATTRIBUTES sa;
1407 HANDLE readHandle, writeHandle;
1408
1409 if (!pfds)
1410 {
1411 *_errno() = EINVAL;
1412 return -1;
1413 }
1414
1415 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
1416 sa.bInheritHandle = !(textmode & _O_NOINHERIT);
1417 sa.lpSecurityDescriptor = NULL;
1418 if (CreatePipe(&readHandle, &writeHandle, &sa, psize))
1419 {
1420 unsigned int wxflags = split_oflags(textmode);
1421 int fd;
1422
1423 LOCK_FILES();
1424 fd = alloc_fd(readHandle, wxflags);
1425 if (fd != -1)
1426 {
1427 pfds[0] = fd;
1428 fd = alloc_fd(writeHandle, wxflags);
1429 if (fd != -1)
1430 {
1431 pfds[1] = fd;
1432 ret = 0;
1433 }
1434 else
1435 {
1436 _close(pfds[0]);
1437 CloseHandle(writeHandle);
1438 *_errno() = EMFILE;
1439 }
1440 }
1441 else
1442 {
1443 CloseHandle(readHandle);
1444 CloseHandle(writeHandle);
1445 *_errno() = EMFILE;
1446 }
1447 UNLOCK_FILES();
1448 }
1449 else
1450 __set_errno(GetLastError());
1451
1452 return ret;
1453 }
1454
1455 /*********************************************************************
1456 * _sopen (MSVCRT.@)
1457 */
1458 int CDECL _sopen( const char *path, int oflags, int shflags, ... )
1459 {
1460 va_list ap;
1461 int pmode;
1462 DWORD access = 0, creation = 0, attrib;
1463 DWORD sharing;
1464 int wxflag = 0, fd;
1465 HANDLE hand;
1466 SECURITY_ATTRIBUTES sa;
1467
1468
1469 TRACE(":file (%s) oflags: 0x%04x shflags: 0x%04x\n",
1470 path, oflags, shflags);
1471
1472 wxflag = split_oflags(oflags);
1473 switch (oflags & (_O_RDONLY | _O_WRONLY | _O_RDWR))
1474 {
1475 case _O_RDONLY: access |= GENERIC_READ; break;
1476 case _O_WRONLY: access |= GENERIC_WRITE; break;
1477 case _O_RDWR: access |= GENERIC_WRITE | GENERIC_READ; break;
1478 }
1479
1480 if (oflags & _O_CREAT)
1481 {
1482 va_start(ap, shflags);
1483 pmode = va_arg(ap, int);
1484 va_end(ap);
1485
1486 if(pmode & ~(_S_IREAD | _S_IWRITE))
1487 FIXME(": pmode 0x%04x ignored\n", pmode);
1488 else
1489 WARN(": pmode 0x%04x ignored\n", pmode);
1490
1491 if (oflags & _O_EXCL)
1492 creation = CREATE_NEW;
1493 else if (oflags & _O_TRUNC)
1494 creation = CREATE_ALWAYS;
1495 else
1496 creation = OPEN_ALWAYS;
1497 }
1498 else /* no _O_CREAT */
1499 {
1500 if (oflags & _O_TRUNC)
1501 creation = TRUNCATE_EXISTING;
1502 else
1503 creation = OPEN_EXISTING;
1504 }
1505
1506 switch( shflags )
1507 {
1508 case _SH_DENYRW:
1509 sharing = 0L;
1510 break;
1511 case _SH_DENYWR:
1512 sharing = FILE_SHARE_READ;
1513 break;
1514 case _SH_DENYRD:
1515 sharing = FILE_SHARE_WRITE;
1516 break;
1517 case _SH_DENYNO:
1518 sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
1519 break;
1520 default:
1521 ERR( "Unhandled shflags 0x%x\n", shflags );
1522 return -1;
1523 }
1524 attrib = FILE_ATTRIBUTE_NORMAL;
1525
1526 if (oflags & _O_TEMPORARY)
1527 {
1528 attrib |= FILE_FLAG_DELETE_ON_CLOSE;
1529 access |= DELETE;
1530 sharing |= FILE_SHARE_DELETE;
1531 }
1532
1533 sa.nLength = sizeof( SECURITY_ATTRIBUTES );
1534 sa.lpSecurityDescriptor = NULL;
1535 sa.bInheritHandle = (oflags & _O_NOINHERIT) ? FALSE : TRUE;
1536
1537 hand = CreateFileA(path, access, sharing, &sa, creation, attrib, 0);
1538
1539 if (hand == INVALID_HANDLE_VALUE) {
1540 WARN(":failed-last error (%d)\n",GetLastError());
1541 __set_errno(GetLastError());
1542 return -1;
1543 }
1544
1545 fd = alloc_fd(hand, wxflag);
1546
1547 TRACE(":fd (%d) handle (%p)\n",fd, hand);
1548 return fd;
1549 }
1550
1551 /*********************************************************************
1552 * _wsopen (MSVCRT.@)
1553 */
1554 int CDECL _wsopen( const wchar_t* path, int oflags, int shflags, ... )
1555 {
1556 const unsigned int len = strlenW(path);
1557 char *patha = calloc(len + 1,1);
1558 va_list ap;
1559 int pmode;
1560
1561 va_start(ap, shflags);
1562 pmode = va_arg(ap, int);
1563 va_end(ap);
1564
1565 if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
1566 {
1567 int retval = _sopen(patha,oflags,shflags,pmode);
1568 free(patha);
1569 return retval;
1570 }
1571
1572 __set_errno(GetLastError());
1573 return -1;
1574 }
1575
1576 /*********************************************************************
1577 * _open (MSVCRT.@)
1578 */
1579 int CDECL _open( const char *path, int flags, ... )
1580 {
1581 va_list ap;
1582
1583 if (flags & _O_CREAT)
1584 {
1585 int pmode;
1586 va_start(ap, flags);
1587 pmode = va_arg(ap, int);
1588 va_end(ap);
1589 return _sopen( path, flags, _SH_DENYNO, pmode );
1590 }
1591 else
1592 return _sopen( path, flags, _SH_DENYNO);
1593 }
1594
1595 /*********************************************************************
1596 * _wopen (MSVCRT.@)
1597 */
1598 int CDECL _wopen(const wchar_t *path,int flags,...)
1599 {
1600 const unsigned int len = strlenW(path);
1601 char *patha = calloc(len + 1,1);
1602 va_list ap;
1603 int pmode;
1604
1605 va_start(ap, flags);
1606 pmode = va_arg(ap, int);
1607 va_end(ap);
1608
1609 if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
1610 {
1611 int retval = _open(patha,flags,pmode);
1612 free(patha);
1613 return retval;
1614 }
1615
1616 __set_errno(GetLastError());
1617 return -1;
1618 }
1619
1620 /*********************************************************************
1621 * _creat (MSVCRT.@)
1622 */
1623 int CDECL _creat(const char *path, int flags)
1624 {
1625 int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
1626 return _open(path, usedFlags);
1627 }
1628
1629 /*********************************************************************
1630 * _wcreat (MSVCRT.@)
1631 */
1632 int CDECL _wcreat(const wchar_t *path, int flags)
1633 {
1634 int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
1635 return _wopen(path, usedFlags);
1636 }
1637
1638 /*********************************************************************
1639 * _open_osfhandle (MSVCRT.@)
1640 */
1641 int CDECL _open_osfhandle(long handle, int oflags)
1642 {
1643 int fd;
1644
1645 /* _O_RDONLY (0) always matches, so set the read flag
1646 * MFC's CStdioFile clears O_RDONLY (0)! if it wants to write to the
1647 * file, so set the write flag. It also only sets _O_TEXT if it wants
1648 * text - it never sets _O_BINARY.
1649 */
1650 /* don't let split_oflags() decide the mode if no mode is passed */
1651 if (!(oflags & (_O_BINARY | _O_TEXT)))
1652 oflags |= _O_BINARY;
1653
1654 fd = alloc_fd((HANDLE)handle, split_oflags(oflags));
1655 TRACE(":handle (%ld) fd (%d) flags 0x%08x\n", handle, fd, oflags);
1656 return fd;
1657 }
1658
1659 /*********************************************************************
1660 * _rmtmp (MSVCRT.@)
1661 */
1662 int CDECL _rmtmp(void)
1663 {
1664 int num_removed = 0, i;
1665
1666 LOCK_FILES();
1667 for (i = 3; i < stream_idx; i++)
1668 if (fstreams[i] && fstreams[i]->_tmpfname)
1669 {
1670 fclose(fstreams[i]);
1671 num_removed++;
1672 }
1673 UNLOCK_FILES();
1674
1675 if (num_removed)
1676 TRACE(":removed (%d) temp files\n",num_removed);
1677 return num_removed;
1678 }
1679
1680 /*********************************************************************
1681 * (internal) remove_cr
1682 *
1683 * Translate all \r\n to \n inplace.
1684 * return the number of \r removed
1685 * Corner cases required by some apps:
1686 * \r\r\n -> \r\n
1687 * BUG: should save state across calls somehow, so CR LF that
1688 * straddles buffer boundary gets recognized properly?
1689 */
1690 static unsigned int remove_cr(char *buf, unsigned int count)
1691 {
1692 unsigned int i, j;
1693
1694 for (i=0, j=0; j < count; j++)
1695 if ((buf[j] != '\r') || ((j+1) < count && buf[j+1] != '\n'))
1696 buf[i++] = buf[j];
1697
1698 return count - i;
1699 }
1700
1701 /*********************************************************************
1702 * (internal) read_i
1703 */
1704 static int read_i(int fd, void *buf, unsigned int count)
1705 {
1706 DWORD num_read;
1707 char *bufstart = buf;
1708 HANDLE hand = fdtoh(fd);
1709
1710 if (fdesc[fd].wxflag & WX_READEOF) {
1711 fdesc[fd].wxflag |= WX_ATEOF;
1712 TRACE("already at EOF, returning 0\n");
1713 return 0;
1714 }
1715 /* Don't trace small reads, it gets *very* annoying */
1716 if (count > 4)
1717 TRACE(":fd (%d) handle (%p) buf (%p) len (%d)\n",fd,hand,buf,count);
1718 if (hand == INVALID_HANDLE_VALUE)
1719 return -1;
1720
1721 /* Reading single bytes in O_TEXT mode makes things slow
1722 * So read big chunks
1723 */
1724 if (ReadFile(hand, bufstart, count, &num_read, NULL))
1725 {
1726 if (fdesc[fd].wxflag & WX_TEXT)
1727 {
1728 int i;
1729 /* in text mode, a ctrl-z signals EOF */
1730 for (i=0; i<num_read; i++)
1731 {
1732 if (bufstart[i] == 0x1a)
1733 {
1734 num_read = i;
1735 fdesc[fd].wxflag |= (WX_ATEOF|WX_READEOF);
1736 TRACE(":^Z EOF %s\n",debugstr_an(buf,num_read));
1737 break;
1738 }
1739 }
1740 }
1741 if (count != 0 && num_read == 0)
1742 {
1743 fdesc[fd].wxflag |= (WX_ATEOF|WX_READEOF);
1744 TRACE(":EOF %s\n",debugstr_an(buf,num_read));
1745 }
1746 }
1747 else
1748 {
1749 if (GetLastError() == ERROR_BROKEN_PIPE)
1750 {
1751 TRACE(":end-of-pipe\n");
1752 fdesc[fd].wxflag |= (WX_ATEOF|WX_READEOF);
1753 return 0;
1754 }
1755 else
1756 {
1757 TRACE(":failed-last error (%d)\n",GetLastError());
1758 return -1;
1759 }
1760 }
1761
1762 if (count > 4)
1763 TRACE("(%u), %s\n",num_read,debugstr_an(buf, num_read));
1764 return num_read;
1765 }
1766
1767 /*********************************************************************
1768 * _read (MSVCRT.@)
1769 */
1770 int CDECL _read(int fd, void *buf, unsigned int count)
1771 {
1772 int num_read;
1773 num_read = read_i(fd, buf, count);
1774 if (num_read>0 && fdesc[fd].wxflag & WX_TEXT)
1775 {
1776 num_read -= remove_cr(buf,num_read);
1777 }
1778 return num_read;
1779 }
1780
1781 /*********************************************************************
1782 * _setmode (MSVCRT.@)
1783 */
1784 int CDECL _setmode(int fd,int mode)
1785 {
1786 int ret = fdesc[fd].wxflag & WX_TEXT ? _O_TEXT : _O_BINARY;
1787 if (mode & (~(_O_TEXT|_O_BINARY)))
1788 FIXME("fd (%d) mode (0x%08x) unknown\n",fd,mode);
1789 if ((mode & _O_TEXT) == _O_TEXT)
1790 fdesc[fd].wxflag |= WX_TEXT;
1791 else
1792 fdesc[fd].wxflag &= ~WX_TEXT;
1793 return ret;
1794 }
1795
1796 /*********************************************************************
1797 * _stat64 (MSVCRT.@)
1798 */
1799 int CDECL _stat64(const char* path, struct __stat64 * buf)
1800 {
1801 DWORD dw;
1802 WIN32_FILE_ATTRIBUTE_DATA hfi;
1803 unsigned short mode = ALL_S_IREAD;
1804 int plen;
1805
1806 TRACE(":file (%s) buf(%p)\n",path,buf);
1807
1808 if (!GetFileAttributesExA(path, GetFileExInfoStandard, &hfi))
1809 {
1810 TRACE("failed (%d)\n",GetLastError());
1811 __set_errno(ERROR_FILE_NOT_FOUND);
1812 return -1;
1813 }
1814
1815 memset(buf,0,sizeof(struct __stat64));
1816
1817 /* FIXME: rdev isn't drive num, despite what the docs say-what is it?
1818 Bon 011120: This FIXME seems incorrect
1819 Also a letter as first char isn't enough to be classified
1820 as a drive letter
1821 */
1822 if (isalpha(*path)&& (*(path+1)==':'))
1823 buf->st_dev = buf->st_rdev = toupper(*path) - 'A'; /* drive num */
1824 else
1825 buf->st_dev = buf->st_rdev = _getdrive() - 1;
1826
1827 plen = strlen(path);
1828
1829 /* Dir, or regular file? */
1830 if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1831 (path[plen-1] == '\\'))
1832 mode |= (_S_IFDIR | ALL_S_IEXEC);
1833 else
1834 {
1835 mode |= _S_IFREG;
1836 /* executable? */
1837 if (plen > 6 && path[plen-4] == '.') /* shortest exe: "\x.exe" */
1838 {
1839 unsigned int ext = tolower(path[plen-1]) | (tolower(path[plen-2]) << 8) |
1840 (tolower(path[plen-3]) << 16);
1841 if (ext == EXE || ext == BAT || ext == CMD || ext == COM)
1842 mode |= ALL_S_IEXEC;
1843 }
1844 }
1845
1846 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1847 mode |= ALL_S_IWRITE;
1848
1849 buf->st_mode = mode;
1850 buf->st_nlink = 1;
1851 buf->st_size = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
1852 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
1853 buf->st_atime = dw;
1854 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
1855 buf->st_mtime = buf->st_ctime = dw;
1856 TRACE("%d %d 0x%08lx%08lx %ld %ld %ld\n", buf->st_mode,buf->st_nlink,
1857 (long)(buf->st_size >> 32),(long)buf->st_size,
1858 (long)buf->st_atime,(long)buf->st_mtime,(long)buf->st_ctime);
1859 return 0;
1860 }
1861
1862 /*********************************************************************
1863 * _stati64 (MSVCRT.@)
1864 */
1865 int CDECL _stati64(const char* path, struct _stati64 * buf)
1866 {
1867 int ret;
1868 struct __stat64 buf64;
1869
1870 ret = _stat64(path, &buf64);
1871 if (!ret)
1872 stat64_to_stati64(&buf64, buf);
1873 return ret;
1874 }
1875
1876 /*********************************************************************
1877 * _stat (MSVCRT.@)
1878 */
1879 int CDECL _stat(const char* path, struct _stat * buf)
1880 { int ret;
1881 struct __stat64 buf64;
1882
1883 ret = _stat64( path, &buf64);
1884 if (!ret)
1885 stat64_to_stat(&buf64, buf);
1886 return ret;
1887 }
1888
1889 /*********************************************************************
1890 * _wstat64 (MSVCRT.@)
1891 */
1892 int CDECL _wstat64(const wchar_t* path, struct __stat64 * buf)
1893 {
1894 DWORD dw;
1895 WIN32_FILE_ATTRIBUTE_DATA hfi;
1896 unsigned short mode = ALL_S_IREAD;
1897 int plen;
1898
1899 TRACE(":file (%s) buf(%p)\n",debugstr_w(path),buf);
1900
1901 if (!GetFileAttributesExW(path, GetFileExInfoStandard, &hfi))
1902 {
1903 TRACE("failed (%d)\n",GetLastError());
1904 __set_errno(ERROR_FILE_NOT_FOUND);
1905 return -1;
1906 }
1907
1908 memset(buf,0,sizeof(struct __stat64));
1909
1910 /* FIXME: rdev isn't drive num, despite what the docs says-what is it? */
1911 if (iswalpha(*path))
1912 buf->st_dev = buf->st_rdev = toupperW(*path - 'A'); /* drive num */
1913 else
1914 buf->st_dev = buf->st_rdev = _getdrive() - 1;
1915
1916 plen = strlenW(path);
1917
1918 /* Dir, or regular file? */
1919 if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1920 (path[plen-1] == '\\'))
1921 mode |= (_S_IFDIR | ALL_S_IEXEC);
1922 else
1923 {
1924 mode |= _S_IFREG;
1925 /* executable? */
1926 if (plen > 6 && path[plen-4] == '.') /* shortest exe: "\x.exe" */
1927 {
1928 ULONGLONG ext = tolowerW(path[plen-1]) | (tolowerW(path[plen-2]) << 16) |
1929 ((ULONGLONG)tolowerW(path[plen-3]) << 32);
1930 if (ext == WCEXE || ext == WCBAT || ext == WCCMD || ext == WCCOM)
1931 mode |= ALL_S_IEXEC;
1932 }
1933 }
1934
1935 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1936 mode |= ALL_S_IWRITE;
1937
1938 buf->st_mode = mode;
1939 buf->st_nlink = 1;
1940 buf->st_size = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
1941 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
1942 buf->st_atime = dw;
1943 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
1944 buf->st_mtime = buf->st_ctime = dw;
1945 TRACE("%d %d 0x%08lx%08lx %ld %ld %ld\n", buf->st_mode,buf->st_nlink,
1946 (long)(buf->st_size >> 32),(long)buf->st_size,
1947 (long)buf->st_atime,(long)buf->st_mtime,(long)buf->st_ctime);
1948 return 0;
1949 }
1950
1951 /*********************************************************************
1952 * _wstati64 (MSVCRT.@)
1953 */
1954 int CDECL _wstati64(const wchar_t* path, struct _stati64 * buf)
1955 {
1956 int ret;
1957 struct __stat64 buf64;
1958
1959 ret = _wstat64(path, &buf64);
1960 if (!ret)
1961 stat64_to_stati64(&buf64, buf);
1962 return ret;
1963 }
1964
1965 /*********************************************************************
1966 * _wstat (MSVCRT.@)
1967 */
1968 int CDECL _wstat(const wchar_t* path, struct _stat * buf)
1969 {
1970 int ret;
1971 struct __stat64 buf64;
1972
1973 ret = _wstat64( path, &buf64 );
1974 if (!ret) stat64_to_stat(&buf64, buf);
1975 return ret;
1976 }
1977
1978 /*********************************************************************
1979 * _tell (MSVCRT.@)
1980 */
1981 long CDECL _tell(int fd)
1982 {
1983 return _lseek(fd, 0, SEEK_CUR);
1984 }
1985
1986 /*********************************************************************
1987 * _telli64 (MSVCRT.@)
1988 */
1989 __int64 CDECL _telli64(int fd)
1990 {
1991 return _lseeki64(fd, 0, SEEK_CUR);
1992 }
1993
1994 /*********************************************************************
1995 * _tempnam (MSVCRT.@)
1996 */
1997 char * CDECL _tempnam(const char *dir, const char *prefix)
1998 {
1999 char tmpbuf[MAX_PATH];
2000 const char *tmp_dir = getenv("TMP");
2001
2002 if (tmp_dir) dir = tmp_dir;
2003
2004 TRACE("dir (%s) prefix (%s)\n",dir,prefix);
2005 if (GetTempFileNameA(dir,prefix,0,tmpbuf))
2006 {
2007 TRACE("got name (%s)\n",tmpbuf);
2008 DeleteFileA(tmpbuf);
2009 return _strdup(tmpbuf);
2010 }
2011 TRACE("failed (%d)\n",GetLastError());
2012 return NULL;
2013 }
2014
2015 /*********************************************************************
2016 * _wtempnam (MSVCRT.@)
2017 */
2018 wchar_t * CDECL _wtempnam(const wchar_t *dir, const wchar_t *prefix)
2019 {
2020 wchar_t tmpbuf[MAX_PATH];
2021
2022 TRACE("dir (%s) prefix (%s)\n",debugstr_w(dir),debugstr_w(prefix));
2023 if (GetTempFileNameW(dir,prefix,0,tmpbuf))
2024 {
2025 TRACE("got name (%s)\n",debugstr_w(tmpbuf));
2026 DeleteFileW(tmpbuf);
2027 return _wcsdup(tmpbuf);
2028 }
2029 TRACE("failed (%d)\n",GetLastError());
2030 return NULL;
2031 }
2032
2033 /*********************************************************************
2034 * _umask (MSVCRT.@)
2035 */
2036 int CDECL _umask(int umask)
2037 {
2038 int old_umask = umask;
2039 TRACE("(%d)\n",umask);
2040 MSVCRT_umask = umask;
2041 return old_umask;
2042 }
2043
2044 /*********************************************************************
2045 * _utime (MSVCRT.@)
2046 */
2047 int CDECL _utime(const char* path, struct _utimbuf *t)
2048 {
2049 int fd = _open(path, _O_WRONLY | _O_BINARY);
2050
2051 if (fd > 0)
2052 {
2053 int retVal = _futime(fd, t);
2054 _close(fd);
2055 return retVal;
2056 }
2057 return -1;
2058 }
2059
2060 /*********************************************************************
2061 * _wutime (MSVCRT.@)
2062 */
2063 int CDECL _wutime(const wchar_t* path, struct _utimbuf *t)
2064 {
2065 int fd = _wopen(path, _O_WRONLY | _O_BINARY);
2066
2067 if (fd > 0)
2068 {
2069 int retVal = _futime(fd, t);
2070 _close(fd);
2071 return retVal;
2072 }
2073 return -1;
2074 }
2075
2076 /*********************************************************************
2077 * _write (MSVCRT.@)
2078 */
2079 int CDECL _write(int fd, const void* buf, unsigned int count)
2080 {
2081 DWORD num_written;
2082 HANDLE hand = fdtoh(fd);
2083
2084 /* Don't trace small writes, it gets *very* annoying */
2085 #if 0
2086 if (count > 32)
2087 TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
2088 #endif
2089 if (hand == INVALID_HANDLE_VALUE)
2090 {
2091 *_errno() = EBADF;
2092 return -1;
2093 }
2094
2095 /* If appending, go to EOF */
2096 if (fdesc[fd].wxflag & WX_APPEND)
2097 _lseek(fd, 0, FILE_END);
2098
2099 if (!(fdesc[fd].wxflag & WX_TEXT))
2100 {
2101 if (WriteFile(hand, buf, count, &num_written, NULL)
2102 && (num_written == count))
2103 return num_written;
2104 TRACE("WriteFile (fd %d, hand %p) failed-last error (%d)\n", fd,
2105 hand, GetLastError());
2106 *_errno() = ENOSPC;
2107 }
2108 else
2109 {
2110 unsigned int i, j, nr_lf;
2111 char *p = NULL;
2112 const char *q;
2113 const char *s = (const char *)buf, *buf_start = (const char *)buf;
2114 /* find number of \n ( without preceding \r ) */
2115 for ( nr_lf=0,i = 0; i <count; i++)
2116 {
2117 if (s[i]== '\n')
2118 {
2119 nr_lf++;
2120 /*if ((i >1) && (s[i-1] == '\r')) nr_lf--; */
2121 }
2122 }
2123 if (nr_lf)
2124 {
2125 if ((q = p = malloc(count + nr_lf)))
2126 {
2127 for (s = (const char *)buf, i = 0, j = 0; i < count; i++)
2128 {
2129 if (s[i]== '\n')
2130 {
2131 p[j++] = '\r';
2132 /*if ((i >1) && (s[i-1] == '\r'))j--;*/
2133 }
2134 p[j++] = s[i];
2135 }
2136 }
2137 else
2138 {
2139 FIXME("Malloc failed\n");
2140 nr_lf =0;
2141 q = buf;
2142 }
2143 }
2144 else
2145 q = buf;
2146
2147 if ((WriteFile(hand, q, count+nr_lf, &num_written, NULL) == 0 ) || (num_written != count+nr_lf))
2148 {
2149 TRACE("WriteFile (fd %d, hand %p) failed-last error (%d), num_written %d\n",
2150 fd, hand, GetLastError(), num_written);
2151 *_errno() = ENOSPC;
2152 if(nr_lf)
2153 free(p);
2154 return s - buf_start;
2155 }
2156 else
2157 {
2158 if(nr_lf)
2159 free(p);
2160 return count;
2161 }
2162 }
2163 return -1;
2164 }
2165
2166 /*********************************************************************
2167 * _putw (MSVCRT.@)
2168 */
2169 int CDECL _putw(int val, FILE* file)
2170 {
2171 int len;
2172 len = _write(file->_file, &val, sizeof(val));
2173 if (len == sizeof(val)) return val;
2174 file->_flag |= _IOERR;
2175 return EOF;
2176 }
2177
2178 /*********************************************************************
2179 * fclose (MSVCRT.@)
2180 */
2181 int CDECL fclose(FILE* file)
2182 {
2183 int r, flag;
2184
2185 flag = file->_flag;
2186 free(file->_tmpfname);
2187 file->_tmpfname = NULL;
2188 /* flush stdio buffers */
2189 if(file->_flag & _IOWRT)
2190 fflush(file);
2191 if(file->_flag & _IOMYBUF)
2192 free(file->_base);
2193
2194 r=_close(file->_file);
2195
2196 file->_flag = 0;
2197
2198 return ((r == -1) || (flag & _IOERR) ? EOF : 0);
2199 }
2200
2201 /*********************************************************************
2202 * feof (MSVCRT.@)
2203 */
2204 int CDECL feof(FILE* file)
2205 {
2206 return file->_flag & _IOEOF;
2207 }
2208
2209 /*********************************************************************
2210 * ferror (MSVCRT.@)
2211 */
2212 int CDECL ferror(FILE* file)
2213 {
2214 return file->_flag & _IOERR;
2215 }
2216
2217 /*********************************************************************
2218 * _filbuf (MSVCRT.@)
2219 */
2220 int CDECL _filbuf(FILE* file)
2221 {
2222 /* Allocate buffer if needed */
2223 if(file->_bufsiz == 0 && !(file->_flag & _IONBF) ) {
2224 alloc_buffer(file);
2225 }
2226 if(!(file->_flag & _IOREAD)) {
2227 if(file->_flag & _IORW) {
2228 file->_flag |= _IOREAD;
2229 } else {
2230 return EOF;
2231 }
2232 }
2233 if(file->_flag & _IONBF) {
2234 unsigned char c;
2235 int r;
2236 if ((r = read_i(file->_file,&c,1)) != 1) {
2237 file->_flag |= (r == 0) ? _IOEOF : _IOERR;
2238 return EOF;
2239 }
2240 return c;
2241 } else {
2242 file->_cnt = read_i(file->_file, file->_base, file->_bufsiz);
2243 if(file->_cnt<=0) {
2244 file->_flag |= (file->_cnt == 0) ? _IOEOF : _IOERR;
2245 file->_cnt = 0;
2246 return EOF;
2247 }
2248 file->_cnt--;
2249 file->_ptr = file->_base+1;
2250 return *(unsigned char *)file->_base;
2251 }
2252 }
2253
2254 /*********************************************************************
2255 * fgetc (MSVCRT.@)
2256 */
2257 int CDECL fgetc(FILE* file)
2258 {
2259 unsigned char *i;
2260 unsigned int j;
2261 do {
2262 if (file->_cnt>0) {
2263 file->_cnt--;
2264 i = (unsigned char *)file->_ptr++;
2265 j = *i;
2266 } else
2267 j = _filbuf(file);
2268 if (!(fdesc[file->_file].wxflag & WX_TEXT)
2269 || ((j != '\r') || (file->_cnt && file->_ptr[0] != '\n')))
2270 return j;
2271 } while(1);
2272 }
2273
2274 /*********************************************************************
2275 * _fgetchar (MSVCRT.@)
2276 */
2277 int CDECL _fgetchar(void)
2278 {
2279 return fgetc(stdin);
2280 }
2281
2282 /*********************************************************************
2283 * fgets (MSVCRT.@)
2284 */
2285 char * CDECL fgets(char *s, int size, FILE* file)
2286 {
2287 int cc = EOF;
2288 char * buf_start = s;
2289
2290 TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
2291 file,file->_file,s,size);
2292
2293 while ((size >1) && (cc = fgetc(file)) != EOF && cc != '\n')
2294 {
2295 *s++ = (char)cc;
2296 size --;
2297 }
2298 if ((cc == EOF) && (s == buf_start)) /* If nothing read, return 0*/
2299 {
2300 TRACE(":nothing read\n");
2301 return NULL;
2302 }
2303 if ((cc != EOF) && (size > 1))
2304 *s++ = cc;
2305 *s = '\0';
2306 TRACE(":got %s\n", debugstr_a(buf_start));
2307 return buf_start;
2308 }
2309
2310 /*********************************************************************
2311 * fgetwc (MSVCRT.@)
2312 *
2313 * In _O_TEXT mode, multibyte characters are read from the file, dropping
2314 * the CR from CR/LF combinations
2315 */
2316 wint_t CDECL fgetwc(FILE* file)
2317 {
2318 char c;
2319
2320 if (!(fdesc[file->_file].wxflag & WX_TEXT))
2321 {
2322 wchar_t wc;
2323 int i,j;
2324 char *chp, *wcp;
2325 wcp = (char *)&wc;
2326 for(i=0; i<sizeof(wc); i++)
2327 {
2328 if (file->_cnt>0)
2329 {
2330 file->_cnt--;
2331 chp = file->_ptr++;
2332 wcp[i] = *chp;
2333 }
2334 else
2335 {
2336 j = _filbuf(file);
2337 if(file->_cnt<=0)
2338 {
2339 file->_flag |= (file->_cnt == 0) ? _IOEOF : _IOERR;
2340 file->_cnt = 0;
2341 return WEOF;
2342 }
2343 wcp[i] = j;
2344 }
2345 }
2346 return wc;
2347 }
2348
2349 c = fgetc(file);
2350 if ((*__p___mb_cur_max() > 1) && isleadbyte(c))
2351 {
2352 FIXME("Treat Multibyte characters\n");
2353 }
2354 if (c == EOF)
2355 return WEOF;
2356 else
2357 return (wint_t)c;
2358 }
2359
2360 /*********************************************************************
2361 * _getw (MSVCRT.@)
2362 */
2363 int CDECL _getw(FILE* file)
2364 {
2365 char *ch;
2366 int i, j, k;
2367 ch = (char *)&i;
2368 for (j=0; j<sizeof(int); j++) {
2369 k = fgetc(file);
2370 if (k == EOF) {
2371 file->_flag |= _IOEOF;
2372 return EOF;
2373 }
2374 ch[j] = k;
2375 }
2376 return i;
2377 }
2378
2379 /*********************************************************************
2380 * getwc (MSVCRT.@)
2381 */
2382 wint_t CDECL getwc(FILE* file)
2383 {
2384 return fgetwc(file);
2385 }
2386
2387 /*********************************************************************
2388 * _fgetwchar (MSVCRT.@)
2389 */
2390 wint_t CDECL _fgetwchar(void)
2391 {
2392 return fgetwc(stdin);
2393 }
2394
2395 /*********************************************************************
2396 * getwchar (MSVCRT.@)
2397 */
2398 wint_t CDECL getwchar(void)
2399 {
2400 return _fgetwchar();
2401 }
2402
2403 /*********************************************************************
2404 * fgetws (MSVCRT.@)
2405 */
2406 wchar_t * CDECL fgetws(wchar_t *s, int size, FILE* file)
2407 {
2408 int cc = WEOF;
2409 wchar_t * buf_start = s;
2410
2411 TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
2412 file,file->_file,s,size);
2413
2414 while ((size >1) && (cc = fgetwc(file)) != WEOF && cc != '\n')
2415 {
2416 *s++ = (char)cc;
2417 size --;
2418 }
2419 if ((cc == WEOF) && (s == buf_start)) /* If nothing read, return 0*/
2420 {
2421 TRACE(":nothing read\n");
2422 return NULL;
2423 }
2424 if ((cc != WEOF) && (size > 1))
2425 *s++ = cc;
2426 *s = 0;
2427 TRACE(":got %s\n", debugstr_w(buf_start));
2428 return buf_start;
2429 }
2430
2431 /*********************************************************************
2432 * fwrite (MSVCRT.@)
2433 */
2434 size_t CDECL fwrite(const void *ptr, size_t size, size_t nmemb, FILE* file)
2435 {
2436 size_t wrcnt=size * nmemb;
2437 int written = 0;
2438 if (size == 0)
2439 return 0;
2440 if(file->_cnt) {
2441 int pcnt=(file->_cnt>wrcnt)? wrcnt: file->_cnt;
2442 memcpy(file->_ptr, ptr, pcnt);
2443 file->_cnt -= pcnt;
2444 file->_ptr += pcnt;
2445 written = pcnt;
2446 wrcnt -= pcnt;
2447 ptr = (const char*)ptr + pcnt;
2448 } else if(!(file->_flag & _IOWRT)) {
2449 if(file->_flag & _IORW) {
2450 file->_flag |= _IOWRT;
2451 } else
2452 return 0;
2453 }
2454 if(wrcnt) {
2455 /* Flush buffer */
2456 int res=flush_buffer(file);
2457 if(!res) {
2458 int pwritten = _write(file->_file, ptr, wrcnt);
2459 if (pwritten <= 0)
2460 {
2461 file->_flag |= _IOERR;
2462 pwritten=0;
2463 }
2464 written += pwritten;
2465 }
2466 }
2467 return written / size;
2468 }
2469
2470 /*********************************************************************
2471 * fputwc (MSVCRT.@)
2472 */
2473 wint_t CDECL fputwc(wint_t wc, FILE* file)
2474 {
2475 wchar_t mwc=wc;
2476 char mbchar[10]; // MB_CUR_MAX_CONST
2477 int mb_return;
2478
2479 if (file->_flag & _IOBINARY)
2480 {
2481 if (fwrite( &mwc, sizeof(mwc), 1, file) != 1)
2482 return WEOF;
2483 }
2484 else
2485 {
2486 /* Convert to multibyte in text mode */
2487 mb_return = wctomb(mbchar, mwc);
2488 if (mb_return == -1) return WEOF;
2489
2490 /* Output all characters */
2491 if (fwrite( mbchar, 1, mb_return, file) != 1)
2492 return WEOF;
2493 }
2494
2495 return wc;
2496 }
2497
2498 /*********************************************************************
2499 * _fputwchar (MSVCRT.@)
2500 */
2501 wint_t CDECL _fputwchar(wint_t wc)
2502 {
2503 return fputwc(wc, stdout);
2504 }
2505
2506 /*********************************************************************
2507 * _fsopen (MSVCRT.@)
2508 */
2509 FILE * CDECL _fsopen(const char *path, const char *mode, int share)
2510 {
2511 FILE* file;
2512 int open_flags, stream_flags, fd;
2513
2514 TRACE("(%s,%s)\n",path,mode);
2515
2516 /* map mode string to open() flags. "man fopen" for possibilities. */
2517 if (get_flags(mode, &open_flags, &stream_flags) == -1)
2518 return NULL;
2519
2520 LOCK_FILES();
2521 fd = _sopen(path, open_flags, share, _S_IREAD | _S_IWRITE);
2522 if (fd < 0)
2523 file = NULL;
2524 else if ((file = alloc_fp()) && init_fp(file, fd, stream_flags)
2525 != -1)
2526 TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,mode,file);
2527 else if (file)
2528 {
2529 file->_flag = 0;
2530 file = NULL;
2531 }
2532
2533 TRACE(":got (%p)\n",file);
2534 if (fd >= 0 && !file)
2535 _close(fd);
2536 UNLOCK_FILES();
2537 return file;
2538 }
2539
2540 /*********************************************************************
2541 * _wfsopen (MSVCRT.@)
2542 */
2543 FILE * CDECL _wfsopen(const wchar_t *path, const wchar_t *mode, int share)
2544 {
2545 const unsigned int plen = strlenW(path), mlen = strlenW(mode);
2546 char *patha = calloc(plen + 1, 1);
2547 char *modea = calloc(mlen + 1, 1);
2548
2549 TRACE("(%s,%s)\n",debugstr_w(path),debugstr_w(mode));
2550
2551 if (patha && modea &&
2552 WideCharToMultiByte(CP_ACP,0,path,plen,patha,plen,NULL,NULL) &&
2553 WideCharToMultiByte(CP_ACP,0,mode,mlen,modea,mlen,NULL,NULL))
2554 {
2555 FILE *retval = _fsopen(patha,modea,share);
2556 free(patha);
2557 free(modea);
2558 return retval;
2559 }
2560
2561 __set_errno(GetLastError());
2562 return NULL;
2563 }
2564
2565 /*********************************************************************
2566 * fopen (MSVCRT.@)
2567 */
2568 FILE * CDECL fopen(const char *path, const char *mode)
2569 {
2570 return _fsopen( path, mode, _SH_DENYNO );
2571 }
2572
2573 /*********************************************************************
2574 * _wfopen (MSVCRT.@)
2575 */
2576 FILE * CDECL _wfopen(const wchar_t *path, const wchar_t *mode)
2577 {
2578 return _wfsopen( path, mode, _SH_DENYNO );
2579 }
2580
2581 /* fputc calls _flsbuf which calls fputc */
2582 int CDECL _flsbuf(int c, FILE* file);
2583
2584 /*********************************************************************
2585 * fputc (MSVCRT.@)
2586 */
2587 int CDECL fputc(int c, FILE* file)
2588 {
2589 if(file->_cnt>0) {
2590 *file->_ptr++=c;
2591 file->_cnt--;
2592 if (c == '\n')
2593 {
2594 int res = flush_buffer(file);
2595 return res ? res : c;
2596 }
2597 else
2598 return c;
2599 } else {
2600 return _flsbuf(c, file);
2601 }
2602 }
2603
2604 /*********************************************************************
2605 * _flsbuf (MSVCRT.@)
2606 */
2607 int CDECL _flsbuf(int c, FILE* file)
2608 {
2609 /* Flush output buffer */
2610 if(file->_bufsiz == 0 && !(file->_flag & _IONBF)) {
2611 alloc_buffer(file);
2612 }
2613 if(!(file->_flag & _IOWRT)) {
2614 if(file->_flag & _IORW) {
2615 file->_flag |= _IOWRT;
2616 } else {
2617 return EOF;
2618 }
2619 }
2620 if(file->_bufsiz) {
2621 int res=flush_buffer(file);
2622 return res?res : fputc(c, file);
2623 } else {
2624 unsigned char cc=c;
2625 int len;
2626 len = _write(file->_file, &cc, 1);
2627 if (len == 1) return c;
2628 file->_flag |= _IOERR;
2629 return EOF;
2630 }
2631 }
2632
2633 /*********************************************************************
2634 * _fputchar (MSVCRT.@)
2635 */
2636 int CDECL _fputchar(int c)
2637 {
2638 return fputc(c, stdout);
2639 }
2640
2641 /*********************************************************************
2642 * fread (MSVCRT.@)
2643 */
2644 size_t CDECL fread(void *ptr, size_t size, size_t nmemb, FILE* file)
2645 { size_t rcnt=size * nmemb;
2646 size_t read=0;
2647 int pread=0;
2648
2649 if(!rcnt)
2650 return 0;
2651
2652 /* first buffered data */
2653 if(file->_cnt>0) {
2654 int pcnt= (rcnt>file->_cnt)? file->_cnt:rcnt;
2655 memcpy(ptr, file->_ptr, pcnt);
2656 file->_cnt -= pcnt;
2657 file->_ptr += pcnt;
2658 if (fdesc[file->_file].wxflag & WX_TEXT)
2659 pcnt -= remove_cr(ptr,pcnt);
2660 read += pcnt ;
2661 rcnt -= pcnt ;
2662 ptr = (char*)ptr + pcnt;
2663 } else if(!(file->_flag & _IOREAD )) {
2664 if(file->_flag & _IORW) {
2665 file->_flag |= _IOREAD;
2666 } else
2667 return 0;
2668 }
2669 while(rcnt>0)
2670 {
2671 int i;
2672 /* Fill the buffer on small reads.
2673 * TODO: Use a better buffering strategy.
2674 */
2675 if (!file->_cnt && size*nmemb <= BUFSIZ/2 && !(file->_flag & _IONBF)) {
2676 if (file->_bufsiz == 0) {
2677 alloc_buffer(file);
2678 }
2679 file->_cnt = _read(file->_file, file->_base, file->_bufsiz);
2680 file->_ptr = file->_base;
2681 i = (file->_cnt<rcnt) ? file->_cnt : rcnt;
2682 /* If the buffer fill reaches eof but fread wouldn't, clear eof. */
2683 if (i > 0 && i < file->_cnt) {
2684 fdesc[file->_file].wxflag &= ~WX_ATEOF;
2685 file->_flag &= ~_IOEOF;
2686 }
2687 if (i > 0) {
2688 memcpy(ptr, file->_ptr, i);
2689 file->_cnt -= i;
2690 file->_ptr += i;
2691 }
2692 } else {
2693 i = _read(file->_file,ptr, rcnt);
2694 }
2695 pread += i;
2696 rcnt -= i;
2697 ptr = (char *)ptr+i;
2698 /* expose feof condition in the flags
2699 * MFC tests file->_flag for feof, and doesn't call feof())
2700 */
2701 if ( fdesc[file->_file].wxflag & WX_ATEOF)
2702 file->_flag |= _IOEOF;
2703 else if (i == -1)
2704 {
2705 file->_flag |= _IOERR;
2706 pread = 0;
2707 rcnt = 0;
2708 }
2709 if (i < 1) break;
2710 }
2711 read+=pread;
2712 return read / size;
2713 }
2714
2715 /*********************************************************************
2716 * freopen (MSVCRT.@)
2717 *
2718 */
2719 FILE* CDECL freopen(const char *path, const char *mode,FILE* file)
2720 {
2721 int open_flags, stream_flags, fd;
2722
2723 TRACE(":path (%p) mode (%s) file (%p) fd (%d)\n",path,mode,file,file->_file);
2724
2725 LOCK_FILES();
2726 if (!file || ((fd = file->_file) < 0) || fd > fdend)
2727 file = NULL;
2728 else
2729 {
2730 fclose(file);
2731 /* map mode string to open() flags. "man fopen" for possibilities. */
2732 if (get_flags(mode, &open_flags, &stream_flags) == -1)
2733 file = NULL;
2734 else
2735 {
2736 fd = _open(path, open_flags, _S_IREAD | _S_IWRITE);
2737 if (fd < 0)
2738 file = NULL;
2739 else if (init_fp(file, fd, stream_flags) == -1)
2740 {
2741 file->_flag = 0;
2742 WARN(":failed-last error (%d)\n",GetLastError());
2743 __set_errno(GetLastError());
2744 file = NULL;
2745 }
2746 }
2747 }
2748 UNLOCK_FILES();
2749 return file;
2750 }
2751
2752 /*********************************************************************
2753 * wfreopen (MSVCRT.@)
2754 *
2755 */
2756 FILE* CDECL _wfreopen(const wchar_t *path, const wchar_t *mode,FILE* file)
2757 {
2758 FIXME("UNIMPLEMENTED stub!\n");
2759 return NULL;
2760 }
2761
2762 /*********************************************************************
2763 * fsetpos (MSVCRT.@)
2764 */
2765 int CDECL fsetpos(FILE* file, const fpos_t *pos)
2766 {
2767 /* Note that all this has been lifted 'as is' from fseek */
2768 if(file->_flag & _IOWRT)
2769 flush_buffer(file);
2770
2771 /* Discard buffered input */
2772 file->_cnt = 0;
2773 file->_ptr = file->_base;
2774
2775 /* Reset direction of i/o */
2776 if(file->_flag & _IORW) {
2777 file->_flag &= ~(_IOREAD|_IOWRT);
2778 }
2779
2780 return (_lseeki64(file->_file,*pos,SEEK_SET) == -1) ? -1 : 0;
2781 }
2782
2783 /*********************************************************************
2784 * ftell (MSVCRT.@)
2785 */
2786 LONG CDECL ftell(FILE* file)
2787 {
2788 int off=0;
2789 long pos;
2790 if(file->_bufsiz) {
2791 if( file->_flag & _IOWRT ) {
2792 off = file->_ptr - file->_base;
2793 } else {
2794 off = -file->_cnt;
2795 }
2796 }
2797 pos = _tell(file->_file);
2798 if(pos == -1) return pos;
2799 return off + pos;
2800 }
2801
2802 /*********************************************************************
2803 * fgetpos (MSVCRT.@)
2804 */
2805 int CDECL fgetpos(FILE* file, fpos_t *pos)
2806 {
2807 /* This code has been lifted form the ftell function */
2808 int off=0;
2809
2810 *pos = _lseeki64(file->_file,0,SEEK_CUR);
2811
2812 if (*pos == -1) return -1;
2813
2814 if(file->_bufsiz) {
2815 if( file->_flag & _IOWRT ) {
2816 off = file->_ptr - file->_base;
2817 } else {
2818 off = -file->_cnt;
2819 }
2820 }
2821 *pos += off;
2822
2823 return 0;
2824 }
2825
2826 /*********************************************************************
2827 * fputs (MSVCRT.@)
2828 */
2829 int CDECL fputs(const char *s, FILE* file)
2830 {
2831 size_t i, len = strlen(s);
2832 if (!(fdesc[file->_file].wxflag & WX_TEXT))
2833 return fwrite(s,sizeof(*s),len,file) == len ? 0 : EOF;
2834 for (i=0; i<len; i++)
2835 if (fputc(s[i], file) == EOF)
2836 return EOF;
2837 return 0;
2838 }
2839
2840 /*********************************************************************
2841 * fputws (MSVCRT.@)
2842 */
2843 int CDECL fputws(const wchar_t *s, FILE* file)
2844 {
2845 size_t i, len = strlenW(s);
2846 if (!(fdesc[file->_file].wxflag & WX_TEXT))
2847 return fwrite(s,sizeof(*s),len,file) == len ? 0 : EOF;
2848 for (i=0; i<len; i++)
2849 {
2850 if ((s[i] == '\n') && (fputc('\r', file) == EOF))
2851 return WEOF;
2852 if (fputwc(s[i], file) == WEOF)
2853 return WEOF;
2854 }
2855 return 0;
2856 }
2857
2858 /*********************************************************************
2859 * getchar (MSVCRT.@)
2860 */
2861 int CDECL getchar(void)
2862 {
2863 return fgetc(stdin);
2864 }
2865
2866 /*********************************************************************
2867 * getc (MSVCRT.@)
2868 */
2869 int CDECL getc(FILE* file)
2870 {
2871 return fgetc(file);
2872 }
2873
2874 /*********************************************************************
2875 * gets (MSVCRT.@)
2876 */
2877 char * CDECL gets(char *buf)
2878 {
2879 int cc;
2880 char * buf_start = buf;
2881
2882 for(cc = fgetc(stdin); cc != EOF && cc != '\n';
2883 cc = fgetc(stdin))
2884 if(cc != '\r') *buf++ = (char)cc;
2885
2886 *buf = '\0';
2887
2888 TRACE("got '%s'\n", buf_start);
2889 return buf_start;
2890 }
2891
2892 /*********************************************************************
2893 * _getws (MSVCRT.@)
2894 */
2895 wchar_t* CDECL _getws(wchar_t* buf)
2896 {
2897 wint_t cc;
2898 wchar_t* ws = buf;
2899
2900 for (cc = fgetwc(stdin); cc != WEOF && cc != '\n';
2901 cc = fgetwc(stdin))
2902 {
2903 if (cc != '\r')
2904 *buf++ = (wchar_t)cc;
2905 }
2906 *buf = '\0';
2907
2908 TRACE("got %s\n", debugstr_w(ws));
2909 return ws;
2910 }
2911
2912 /*********************************************************************
2913 * putc (MSVCRT.@)
2914 */
2915 int CDECL putc(int c, FILE* file)
2916 {
2917 return fputc(c, file);
2918 }
2919
2920 /*********************************************************************
2921 * putchar (MSVCRT.@)
2922 */
2923 int CDECL putchar(int c)
2924 {
2925 return fputc(c, stdout);
2926 }
2927
2928 /*********************************************************************
2929 * puts (MSVCRT.@)
2930 */
2931 int CDECL puts(const char *s)
2932 {
2933 size_t len = strlen(s);
2934 if (fwrite(s,sizeof(*s),len,stdout) != len) return EOF;
2935 return fwrite("\n",1,1,stdout) == 1 ? 0 : EOF;
2936 }
2937
2938 /*********************************************************************
2939 * _putws (MSVCRT.@)
2940 */
2941 int CDECL _putws(const wchar_t *s)
2942 {
2943 static const wchar_t nl = '\n';
2944 size_t len = strlenW(s);
2945 if (fwrite(s,sizeof(*s),len,stdout) != len) return EOF;
2946 return fwrite(&nl,sizeof(nl),1,stdout) == 1 ? 0 : EOF;
2947 }
2948
2949 /*********************************************************************
2950 * remove (MSVCRT.@)
2951 */
2952 int CDECL remove(const char *path)
2953 {
2954 TRACE("(%s)\n",path);
2955 if (DeleteFileA(path))
2956 return 0;
2957 TRACE(":failed (%d)\n",GetLastError());
2958 __set_errno(GetLastError());
2959 return -1;
2960 }
2961
2962 /*********************************************************************
2963 * _wremove (MSVCRT.@)
2964 */
2965 int CDECL _wremove(const wchar_t *path)
2966 {
2967 TRACE("(%s)\n",debugstr_w(path));
2968 if (DeleteFileW(path))
2969 return 0;
2970 TRACE(":failed (%d)\n",GetLastError());
2971 __set_errno(GetLastError());
2972 return -1;
2973 }
2974
2975 /*********************************************************************
2976 * rename (MSVCRT.@)
2977 */
2978 int CDECL rename(const char *oldpath,const char *newpath)
2979 {
2980 TRACE(":from %s to %s\n",oldpath,newpath);
2981 if (MoveFileExA(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
2982 return 0;
2983 TRACE(":failed (%d)\n",GetLastError());
2984 __set_errno(GetLastError());
2985 return -1;
2986 }
2987
2988 /*********************************************************************
2989 * _wrename (MSVCRT.@)
2990 */
2991 int CDECL _wrename(const wchar_t *oldpath,const wchar_t *newpath)
2992 {
2993 TRACE(":from %s to %s\n",debugstr_w(oldpath),debugstr_w(newpath));
2994 if (MoveFileExW(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
2995 return 0;
2996 TRACE(":failed (%d)\n",GetLastError());
2997 __set_errno(GetLastError());
2998 return -1;
2999 }
3000
3001 /*********************************************************************
3002 * setvbuf (MSVCRT.@)
3003 */
3004 int CDECL setvbuf(FILE* file, char *buf, int mode, size_t size)
3005 {
3006 /* TODO: Check if file busy */
3007 if(file->_bufsiz) {
3008 free(file->_base);
3009 file->_bufsiz = 0;
3010 file->_cnt = 0;
3011 }
3012 if(mode == _IOFBF) {
3013 file->_flag &= ~_IONBF;
3014 file->_base = file->_ptr = buf;
3015 if(buf) {
3016 file->_bufsiz = size;
3017 }
3018 } else {
3019 file->_flag |= _IONBF;
3020 }
3021 return 0;
3022 }
3023
3024 /*********************************************************************
3025 * setbuf (MSVCRT.@)
3026 */
3027 void CDECL setbuf(FILE* file, char *buf)
3028 {
3029 setvbuf(file, buf, buf ? _IOFBF : _IONBF, BUFSIZ);
3030 }
3031
3032 /*********************************************************************
3033 * tmpnam (MSVCRT.@)
3034 */
3035 char * CDECL tmpnam(char *s)
3036 {
3037 static int unique;
3038 char tmpstr[16];
3039 char *p;
3040 int count;
3041 if (s == 0)
3042 s = tmpname;
3043 int_to_base32(GetCurrentProcessId(), tmpstr);
3044 p = s + sprintf(s, "\\s%s.", tmpstr);
3045 for (count = 0; count < TMP_MAX; count++)
3046 {
3047 int_to_base32(unique++, tmpstr);
3048 strcpy(p, tmpstr);
3049 if (GetFileAttributesA(s) == INVALID_FILE_ATTRIBUTES &&
3050 GetLastError() == ERROR_FILE_NOT_FOUND)
3051 break;
3052 }
3053 return s;
3054 }
3055
3056 /*********************************************************************
3057 * wtmpnam (MSVCRT.@)
3058 */
3059 wchar_t * CDECL _wtmpnam(wchar_t *s)
3060 {
3061 ERR("UNIMPLEMENTED!\n");
3062 return NULL;
3063 }
3064
3065 /*********************************************************************
3066 * tmpfile (MSVCRT.@)
3067 */
3068 FILE* CDECL tmpfile(void)
3069 {
3070 char *filename = tmpnam(NULL);
3071 int fd;
3072 FILE* file = NULL;
3073
3074 LOCK_FILES();
3075 fd = _open(filename, _O_CREAT | _O_BINARY | _O_RDWR | _O_TEMPORARY);
3076 if (fd != -1 && (file = alloc_fp()))
3077 {
3078 if (init_fp(file, fd, _O_RDWR) == -1)
3079 {
3080 file->_flag = 0;
3081 file = NULL;
3082 }
3083 else file->_tmpfname = _strdup(filename);
3084 }
3085 UNLOCK_FILES();
3086 return file;
3087 }
3088
3089 /*********************************************************************
3090 * vfprintf (MSVCRT.@)
3091 */
3092 int CDECL vfprintf(FILE* file, const char *format, va_list valist)
3093 {
3094 char buf[2048], *mem = buf;
3095 int written, resize = sizeof(buf), retval;
3096 /* There are two conventions for vsnprintf failing:
3097 * Return -1 if we truncated, or
3098 * Return the number of bytes that would have been written
3099 * The code below handles both cases
3100 */
3101 while ((written = _vsnprintf(mem, resize, format, valist)) == -1 ||
3102 written > resize)
3103 {
3104 resize = (written == -1 ? resize * 2 : written + 1);
3105 if (mem != buf)
3106 free (mem);
3107 if (!(mem = malloc(resize)))
3108 return EOF;
3109 }
3110 retval = fwrite(mem, sizeof(*mem), written, file);
3111 if (mem != buf)
3112 free (mem);
3113 return retval;
3114 }
3115
3116 /*********************************************************************
3117 * vfwprintf (MSVCRT.@)
3118 * FIXME:
3119 * Is final char included in written (then resize is too big) or not
3120 * (then we must test for equality too)?
3121 */
3122 int CDECL vfwprintf(FILE* file, const wchar_t *format, va_list valist)
3123 {
3124 wchar_t buf[2048], *mem = buf;
3125 char mbbuf[2048], *mbmem = mbbuf;
3126 int written, resize = sizeof(buf) / sizeof(wchar_t), retval;
3127 /* See vfprintf comments */
3128 while ((written = _vsnwprintf(mem, resize, format, valist)) == -1 ||
3129 written > resize)
3130 {
3131 resize = (written == -1 ? resize * 2 : written + sizeof(wchar_t));
3132 if (mem != buf)
3133 free (mem);
3134 if (!(mem = malloc(resize*sizeof(*mem))))
3135 return EOF;
3136 }
3137
3138 /* Check if outputting to a text-file */
3139 if (fdesc[file->_file].wxflag & WX_TEXT)
3140 {
3141 /* Convert to multibyte then */
3142 written = wcstombs(NULL, mem, 0);
3143
3144 if (written >= sizeof(mbbuf) && (written != (int)-1))
3145 mbmem = malloc(written + 1);
3146
3147 wcstombs(mbmem, mem, written);
3148 retval = fwrite(mbmem, 1, written, file);
3149
3150 if (mbmem != mbbuf)
3151 free(mbmem);
3152 }
3153 else
3154 {
3155 retval = fwrite(mem, sizeof(*mem), written, file);
3156 }
3157
3158 if (mem != buf)
3159 free (mem);
3160
3161 return retval;
3162 }
3163
3164 /*********************************************************************
3165 * vprintf (MSVCRT.@)
3166 */
3167 int CDECL vprintf(const char *format, va_list valist)
3168 {
3169 return vfprintf(stdout,format,valist);
3170 }
3171
3172 /*********************************************************************
3173 * vwprintf (MSVCRT.@)
3174 */
3175 int CDECL vwprintf(const wchar_t *format, va_list valist)
3176 {
3177 return vfwprintf(stdout,format,valist);
3178 }
3179
3180 /*********************************************************************
3181 * fprintf (MSVCRT.@)
3182 */
3183 int CDECL fprintf(FILE* file, const char *format, ...)
3184 {
3185 va_list valist;
3186 int res;
3187 va_start(valist, format);
3188 res = vfprintf(file, format, valist);
3189 va_end(valist);
3190 return res;
3191 }
3192
3193 /*********************************************************************
3194 * fwprintf (MSVCRT.@)
3195 */
3196 int CDECL fwprintf(FILE* file, const wchar_t *format, ...)
3197 {
3198 va_list valist;
3199 int res;
3200 va_start(valist, format);
3201 res = vfwprintf(file, format, valist);
3202 va_end(valist);
3203 return res;
3204 }
3205
3206 /*********************************************************************
3207 * printf (MSVCRT.@)
3208 */
3209 int CDECL printf(const char *format, ...)
3210 {
3211 va_list valist;
3212 int res;
3213 va_start(valist, format);
3214 res = vfprintf(stdout, format, valist);
3215 va_end(valist);
3216 return res;
3217 }
3218
3219 /*********************************************************************
3220 * ungetc (MSVCRT.@)
3221 */
3222 int CDECL ungetc(int c, FILE * file)
3223 {
3224 if (c == EOF)
3225 return EOF;
3226 if(file->_bufsiz == 0 && !(file->_flag & _IONBF)) {
3227 alloc_buffer(file);
3228 file->_ptr++;
3229 }
3230 if(file->_ptr>file->_base) {
3231 file->_ptr--;
3232 *file->_ptr=c;
3233 file->_cnt++;
3234 clearerr(file);
3235 return c;
3236 }
3237 return EOF;
3238 }
3239
3240 /*********************************************************************
3241 * ungetwc (MSVCRT.@)
3242 */
3243 wint_t CDECL ungetwc(wint_t wc, FILE * file)
3244 {
3245 wchar_t mwc = wc;
3246 char * pp = (char *)&mwc;
3247 int i;
3248 for(i=sizeof(wchar_t)-1;i>=0;i--) {
3249 if(pp[i] != ungetc(pp[i],file))
3250 return WEOF;
3251 }
3252 return mwc;
3253 }
3254
3255 /*********************************************************************
3256 * wprintf (MSVCRT.@)
3257 */
3258 int CDECL wprintf(const wchar_t *format, ...)
3259 {
3260 va_list valist;
3261 int res;
3262 va_start(valist, format);
3263 res = vwprintf(format, valist);
3264 va_end(valist);
3265 return res;
3266 }
3267
3268 /*********************************************************************
3269 * _getmaxstdio (MSVCRT.@)
3270 */
3271 int CDECL _getmaxstdio(void)
3272 {
3273 FIXME("stub, always returns 512\n");
3274 return 512;
3275 }
3276
3277 /*********************************************************************
3278 * _setmaxstdio_ (MSVCRT.@)
3279 */
3280 int CDECL _setmaxstdio(int newmax)
3281 {
3282 int res;
3283 if( newmax > 2048)
3284 res = -1;
3285 else
3286 res = newmax;
3287 FIXME("stub: setting new maximum for number of simultaneously open files not implemented,returning %d\n",res);
3288 return res;
3289 }
3290
3291 /*********************************************************************
3292 * __pioinfo (MSVCRT.@)
3293 * FIXME: see MAX_FILES define.
3294 */
3295 ioinfo * __pioinfo[] = { /* array of pointers to ioinfo arrays [64] */
3296 &fdesc[0 * 64], &fdesc[1 * 64], &fdesc[2 * 64],
3297 &fdesc[3 * 64], &fdesc[4 * 64], &fdesc[5 * 64],
3298 &fdesc[6 * 64], &fdesc[7 * 64], &fdesc[8 * 64],
3299 &fdesc[9 * 64], &fdesc[10 * 64], &fdesc[11 * 64],
3300 &fdesc[12 * 64], &fdesc[13 * 64], &fdesc[14 * 64],
3301 &fdesc[15 * 64], &fdesc[16 * 64], &fdesc[17 * 64],
3302 &fdesc[18 * 64], &fdesc[19 * 64], &fdesc[20 * 64],
3303 &fdesc[21 * 64], &fdesc[22 * 64], &fdesc[23 * 64],
3304 &fdesc[24 * 64], &fdesc[25 * 64], &fdesc[26 * 64],
3305 &fdesc[27 * 64], &fdesc[28 * 64], &fdesc[29 * 64],
3306 &fdesc[30 * 64], &fdesc[31 * 64]
3307 } ;
3308
3309 /*********************************************************************
3310 * __badioinfo (MSVCRT.@)
3311 */
3312 ioinfo __badioinfo = { INVALID_HANDLE_VALUE, WX_TEXT };