727547076859affdc0c5776c34776f8bc6172908
[reactos.git] / 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] = { { 0 } };
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 free(modea);
1116 return file;
1117 }
1118
1119 /*********************************************************************
1120 * _filelength (MSVCRT.@)
1121 */
1122 LONG CDECL _filelength(int fd)
1123 {
1124 LONG curPos = _lseek(fd, 0, SEEK_CUR);
1125 if (curPos != -1)
1126 {
1127 LONG endPos = _lseek(fd, 0, SEEK_END);
1128 if (endPos != -1)
1129 {
1130 if (endPos != curPos)
1131 _lseek(fd, curPos, SEEK_SET);
1132 return endPos;
1133 }
1134 }
1135 return -1;
1136 }
1137
1138 /*********************************************************************
1139 * _filelengthi64 (MSVCRT.@)
1140 */
1141 __int64 CDECL _filelengthi64(int fd)
1142 {
1143 __int64 curPos = _lseeki64(fd, 0, SEEK_CUR);
1144 if (curPos != -1)
1145 {
1146 __int64 endPos = _lseeki64(fd, 0, SEEK_END);
1147 if (endPos != -1)
1148 {
1149 if (endPos != curPos)
1150 _lseeki64(fd, curPos, SEEK_SET);
1151 return endPos;
1152 }
1153 }
1154 return -1;
1155 }
1156
1157 /*********************************************************************
1158 * _fileno (MSVCRT.@)
1159 */
1160 int CDECL _fileno(FILE* file)
1161 {
1162 TRACE(":FILE* (%p) fd (%d)\n",file,file->_file);
1163 return file->_file;
1164 }
1165
1166 /*********************************************************************
1167 * _fstat64 (MSVCRT.@)
1168 */
1169 int CDECL _fstat64(int fd, struct __stat64* buf)
1170 {
1171 DWORD dw;
1172 DWORD type;
1173 BY_HANDLE_FILE_INFORMATION hfi;
1174 HANDLE hand = fdtoh(fd);
1175
1176 TRACE(":fd (%d) stat (%p)\n",fd,buf);
1177 if (hand == INVALID_HANDLE_VALUE)
1178 return -1;
1179
1180 if (!buf)
1181 {
1182 WARN(":failed-NULL buf\n");
1183 __set_errno(ERROR_INVALID_PARAMETER);
1184 return -1;
1185 }
1186
1187 memset(&hfi, 0, sizeof(hfi));
1188 memset(buf, 0, sizeof(struct __stat64));
1189 type = GetFileType(hand);
1190 if (type == FILE_TYPE_PIPE)
1191 {
1192 buf->st_dev = buf->st_rdev = fd;
1193 buf->st_mode = S_IFIFO;
1194 buf->st_nlink = 1;
1195 }
1196 else if (type == FILE_TYPE_CHAR)
1197 {
1198 buf->st_dev = buf->st_rdev = fd;
1199 buf->st_mode = S_IFCHR;
1200 buf->st_nlink = 1;
1201 }
1202 else /* FILE_TYPE_DISK etc. */
1203 {
1204 if (!GetFileInformationByHandle(hand, &hfi))
1205 {
1206 WARN(":failed-last error (%d)\n",GetLastError());
1207 __set_errno(ERROR_INVALID_PARAMETER);
1208 return -1;
1209 }
1210 buf->st_mode = S_IFREG | S_IREAD;
1211 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1212 buf->st_mode |= S_IWRITE;
1213 buf->st_size = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
1214 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
1215 buf->st_atime = dw;
1216 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
1217 buf->st_mtime = buf->st_ctime = dw;
1218 buf->st_nlink = hfi.nNumberOfLinks;
1219 }
1220 TRACE(":dwFileAttributes = 0x%x, mode set to 0x%x\n",hfi.dwFileAttributes,
1221 buf->st_mode);
1222 return 0;
1223 }
1224
1225 /*********************************************************************
1226 * _fstati64 (MSVCRT.@)
1227 */
1228 int CDECL _fstati64(int fd, struct _stati64* buf)
1229 {
1230 int ret;
1231 struct __stat64 buf64;
1232
1233 ret = _fstat64(fd, &buf64);
1234 if (!ret)
1235 stat64_to_stati64(&buf64, buf);
1236 return ret;
1237 }
1238
1239 /*********************************************************************
1240 * _fstat (MSVCRT.@)
1241 */
1242 int CDECL _fstat(int fd, struct _stat* buf)
1243 { int ret;
1244 struct __stat64 buf64;
1245
1246 ret = _fstat64(fd, &buf64);
1247 if (!ret)
1248 stat64_to_stat(&buf64, buf);
1249 return ret;
1250 }
1251
1252 /*********************************************************************
1253 * _futime (MSVCRT.@)
1254 */
1255 int CDECL _futime(int fd, struct _utimbuf *t)
1256 {
1257 HANDLE hand = fdtoh(fd);
1258 FILETIME at, wt;
1259
1260 if (hand == INVALID_HANDLE_VALUE)
1261 return -1;
1262
1263 if (!t)
1264 {
1265 time_t currTime;
1266 time(&currTime);
1267 RtlSecondsSince1970ToTime(currTime, (LARGE_INTEGER *)&at);
1268 wt = at;
1269 }
1270 else
1271 {
1272 RtlSecondsSince1970ToTime(t->actime, (LARGE_INTEGER *)&at);
1273 if (t->actime == t->modtime)
1274 wt = at;
1275 else
1276 RtlSecondsSince1970ToTime(t->modtime, (LARGE_INTEGER *)&wt);
1277 }
1278
1279 if (!SetFileTime(hand, NULL, &at, &wt))
1280 {
1281 __set_errno(GetLastError());
1282 return -1 ;
1283 }
1284 return 0;
1285 }
1286
1287 /*********************************************************************
1288 * _get_osfhandle (MSVCRT.@)
1289 */
1290 long CDECL _get_osfhandle(int fd)
1291 {
1292 HANDLE hand = fdtoh(fd);
1293 TRACE(":fd (%d) handle (%p)\n",fd,hand);
1294
1295 return (long)hand;
1296 }
1297
1298 /*********************************************************************
1299 * _isatty (MSVCRT.@)
1300 */
1301 int CDECL _isatty(int fd)
1302 {
1303 HANDLE hand = fdtoh(fd);
1304
1305 TRACE(":fd (%d) handle (%p)\n",fd,hand);
1306 if (hand == INVALID_HANDLE_VALUE)
1307 return 0;
1308
1309 return GetFileType(hand) == FILE_TYPE_CHAR? 1 : 0;
1310 }
1311
1312 /*********************************************************************
1313 * _mktemp (MSVCRT.@)
1314 */
1315 char * CDECL _mktemp(char *pattern)
1316 {
1317 int numX = 0;
1318 char *retVal = pattern;
1319 int id;
1320 char letter = 'a';
1321
1322 while(*pattern)
1323 numX = (*pattern++ == 'X')? numX + 1 : 0;
1324 if (numX < 5)
1325 return NULL;
1326 pattern--;
1327 id = GetCurrentProcessId();
1328 numX = 6;
1329 while(numX--)
1330 {
1331 int tempNum = id / 10;
1332 *pattern-- = id - (tempNum * 10) + '0';
1333 id = tempNum;
1334 }
1335 pattern++;
1336 do
1337 {
1338 *pattern = letter++;
1339 if (GetFileAttributesA(retVal) == INVALID_FILE_ATTRIBUTES &&
1340 GetLastError() == ERROR_FILE_NOT_FOUND)
1341 return retVal;
1342 } while(letter <= 'z');
1343 return NULL;
1344 }
1345
1346 /*********************************************************************
1347 * _wmktemp (MSVCRT.@)
1348 */
1349 wchar_t * CDECL _wmktemp(wchar_t *pattern)
1350 {
1351 int numX = 0;
1352 wchar_t *retVal = pattern;
1353 int id;
1354 wchar_t letter = 'a';
1355
1356 while(*pattern)
1357 numX = (*pattern++ == 'X')? numX + 1 : 0;
1358 if (numX < 5)
1359 return NULL;
1360 pattern--;
1361 id = GetCurrentProcessId();
1362 numX = 6;
1363 while(numX--)
1364 {
1365 int tempNum = id / 10;
1366 *pattern-- = id - (tempNum * 10) + '0';
1367 id = tempNum;
1368 }
1369 pattern++;
1370 do
1371 {
1372 if (GetFileAttributesW(retVal) == INVALID_FILE_ATTRIBUTES &&
1373 GetLastError() == ERROR_FILE_NOT_FOUND)
1374 return retVal;
1375 *pattern = letter++;
1376 } while(letter != '|');
1377 return NULL;
1378 }
1379
1380 /*static */unsigned split_oflags(unsigned oflags)
1381 {
1382 int wxflags = 0;
1383 unsigned unsupp; /* until we support everything */
1384
1385 if (oflags & _O_APPEND) wxflags |= WX_APPEND;
1386 if (oflags & _O_BINARY) {/* Nothing to do */}
1387 else if (oflags & _O_TEXT) wxflags |= WX_TEXT;
1388 else if (*__p__fmode() & _O_BINARY) {/* Nothing to do */}
1389 else wxflags |= WX_TEXT; /* default to TEXT*/
1390 if (oflags & _O_NOINHERIT) wxflags |= WX_DONTINHERIT;
1391
1392 if ((unsupp = oflags & ~(
1393 _O_BINARY|_O_TEXT|_O_APPEND|
1394 _O_TRUNC|_O_EXCL|_O_CREAT|
1395 _O_RDWR|_O_WRONLY|_O_TEMPORARY|
1396 _O_NOINHERIT|
1397 _O_SEQUENTIAL|_O_RANDOM|_O_SHORT_LIVED
1398 )))
1399 ERR(":unsupported oflags 0x%04x\n",unsupp);
1400
1401 return wxflags;
1402 }
1403
1404 /*********************************************************************
1405 * _pipe (MSVCRT.@)
1406 */
1407 int CDECL _pipe(int *pfds, unsigned int psize, int textmode)
1408 {
1409 int ret = -1;
1410 SECURITY_ATTRIBUTES sa;
1411 HANDLE readHandle, writeHandle;
1412
1413 if (!pfds)
1414 {
1415 *_errno() = EINVAL;
1416 return -1;
1417 }
1418
1419 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
1420 sa.bInheritHandle = !(textmode & _O_NOINHERIT);
1421 sa.lpSecurityDescriptor = NULL;
1422 if (CreatePipe(&readHandle, &writeHandle, &sa, psize))
1423 {
1424 unsigned int wxflags = split_oflags(textmode);
1425 int fd;
1426
1427 LOCK_FILES();
1428 fd = alloc_fd(readHandle, wxflags);
1429 if (fd != -1)
1430 {
1431 pfds[0] = fd;
1432 fd = alloc_fd(writeHandle, wxflags);
1433 if (fd != -1)
1434 {
1435 pfds[1] = fd;
1436 ret = 0;
1437 }
1438 else
1439 {
1440 _close(pfds[0]);
1441 CloseHandle(writeHandle);
1442 *_errno() = EMFILE;
1443 }
1444 }
1445 else
1446 {
1447 CloseHandle(readHandle);
1448 CloseHandle(writeHandle);
1449 *_errno() = EMFILE;
1450 }
1451 UNLOCK_FILES();
1452 }
1453 else
1454 __set_errno(GetLastError());
1455
1456 return ret;
1457 }
1458
1459 /*********************************************************************
1460 * _sopen (MSVCRT.@)
1461 */
1462 int CDECL _sopen( const char *path, int oflags, int shflags, ... )
1463 {
1464 va_list ap;
1465 int pmode;
1466 DWORD access = 0, creation = 0, attrib;
1467 DWORD sharing;
1468 int wxflag = 0, fd;
1469 HANDLE hand;
1470 SECURITY_ATTRIBUTES sa;
1471
1472
1473 TRACE(":file (%s) oflags: 0x%04x shflags: 0x%04x\n",
1474 path, oflags, shflags);
1475
1476 wxflag = split_oflags(oflags);
1477 switch (oflags & (_O_RDONLY | _O_WRONLY | _O_RDWR))
1478 {
1479 case _O_RDONLY: access |= GENERIC_READ; break;
1480 case _O_WRONLY: access |= GENERIC_WRITE; break;
1481 case _O_RDWR: access |= GENERIC_WRITE | GENERIC_READ; break;
1482 }
1483
1484 if (oflags & _O_CREAT)
1485 {
1486 va_start(ap, shflags);
1487 pmode = va_arg(ap, int);
1488 va_end(ap);
1489
1490 if(pmode & ~(_S_IREAD | _S_IWRITE))
1491 FIXME(": pmode 0x%04x ignored\n", pmode);
1492 else
1493 WARN(": pmode 0x%04x ignored\n", pmode);
1494
1495 if (oflags & _O_EXCL)
1496 creation = CREATE_NEW;
1497 else if (oflags & _O_TRUNC)
1498 creation = CREATE_ALWAYS;
1499 else
1500 creation = OPEN_ALWAYS;
1501 }
1502 else /* no _O_CREAT */
1503 {
1504 if (oflags & _O_TRUNC)
1505 creation = TRUNCATE_EXISTING;
1506 else
1507 creation = OPEN_EXISTING;
1508 }
1509
1510 switch( shflags )
1511 {
1512 case _SH_DENYRW:
1513 sharing = 0L;
1514 break;
1515 case _SH_DENYWR:
1516 sharing = FILE_SHARE_READ;
1517 break;
1518 case _SH_DENYRD:
1519 sharing = FILE_SHARE_WRITE;
1520 break;
1521 case _SH_DENYNO:
1522 sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
1523 break;
1524 default:
1525 ERR( "Unhandled shflags 0x%x\n", shflags );
1526 return -1;
1527 }
1528 attrib = FILE_ATTRIBUTE_NORMAL;
1529
1530 if (oflags & _O_TEMPORARY)
1531 {
1532 attrib |= FILE_FLAG_DELETE_ON_CLOSE;
1533 access |= DELETE;
1534 sharing |= FILE_SHARE_DELETE;
1535 }
1536
1537 sa.nLength = sizeof( SECURITY_ATTRIBUTES );
1538 sa.lpSecurityDescriptor = NULL;
1539 sa.bInheritHandle = (oflags & _O_NOINHERIT) ? FALSE : TRUE;
1540
1541 hand = CreateFileA(path, access, sharing, &sa, creation, attrib, 0);
1542
1543 if (hand == INVALID_HANDLE_VALUE) {
1544 WARN(":failed-last error (%d)\n",GetLastError());
1545 __set_errno(GetLastError());
1546 return -1;
1547 }
1548
1549 fd = alloc_fd(hand, wxflag);
1550
1551 TRACE(":fd (%d) handle (%p)\n",fd, hand);
1552 return fd;
1553 }
1554
1555 /*********************************************************************
1556 * _wsopen (MSVCRT.@)
1557 */
1558 int CDECL _wsopen( const wchar_t* path, int oflags, int shflags, ... )
1559 {
1560 const unsigned int len = strlenW(path);
1561 char *patha = calloc(len + 1,1);
1562 va_list ap;
1563 int pmode;
1564
1565 va_start(ap, shflags);
1566 pmode = va_arg(ap, int);
1567 va_end(ap);
1568
1569 if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
1570 {
1571 int retval = _sopen(patha,oflags,shflags,pmode);
1572 free(patha);
1573 return retval;
1574 }
1575 __set_errno(GetLastError());
1576 free(patha);
1577 return -1;
1578 }
1579
1580 /*********************************************************************
1581 * _open (MSVCRT.@)
1582 */
1583 int CDECL _open( const char *path, int flags, ... )
1584 {
1585 va_list ap;
1586
1587 if (flags & _O_CREAT)
1588 {
1589 int pmode;
1590 va_start(ap, flags);
1591 pmode = va_arg(ap, int);
1592 va_end(ap);
1593 return _sopen( path, flags, _SH_DENYNO, pmode );
1594 }
1595 else
1596 return _sopen( path, flags, _SH_DENYNO);
1597 }
1598
1599 /*********************************************************************
1600 * _wopen (MSVCRT.@)
1601 */
1602 int CDECL _wopen(const wchar_t *path,int flags,...)
1603 {
1604 const unsigned int len = strlenW(path);
1605 char *patha = calloc(len + 1,1);
1606 va_list ap;
1607 int pmode;
1608
1609 va_start(ap, flags);
1610 pmode = va_arg(ap, int);
1611 va_end(ap);
1612
1613 if (patha && WideCharToMultiByte(CP_ACP,0,path,len,patha,len,NULL,NULL))
1614 {
1615 int retval = _open(patha,flags,pmode);
1616 free(patha);
1617 return retval;
1618 }
1619
1620 __set_errno(GetLastError());
1621 return -1;
1622 }
1623
1624 /*********************************************************************
1625 * _creat (MSVCRT.@)
1626 */
1627 int CDECL _creat(const char *path, int flags)
1628 {
1629 int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
1630 return _open(path, usedFlags);
1631 }
1632
1633 /*********************************************************************
1634 * _wcreat (MSVCRT.@)
1635 */
1636 int CDECL _wcreat(const wchar_t *path, int flags)
1637 {
1638 int usedFlags = (flags & _O_TEXT)| _O_CREAT| _O_WRONLY| _O_TRUNC;
1639 return _wopen(path, usedFlags);
1640 }
1641
1642 /*********************************************************************
1643 * _open_osfhandle (MSVCRT.@)
1644 */
1645 int CDECL _open_osfhandle(long handle, int oflags)
1646 {
1647 int fd;
1648
1649 /* _O_RDONLY (0) always matches, so set the read flag
1650 * MFC's CStdioFile clears O_RDONLY (0)! if it wants to write to the
1651 * file, so set the write flag. It also only sets _O_TEXT if it wants
1652 * text - it never sets _O_BINARY.
1653 */
1654 /* don't let split_oflags() decide the mode if no mode is passed */
1655 if (!(oflags & (_O_BINARY | _O_TEXT)))
1656 oflags |= _O_BINARY;
1657
1658 fd = alloc_fd((HANDLE)handle, split_oflags(oflags));
1659 TRACE(":handle (%ld) fd (%d) flags 0x%08x\n", handle, fd, oflags);
1660 return fd;
1661 }
1662
1663 /*********************************************************************
1664 * _rmtmp (MSVCRT.@)
1665 */
1666 int CDECL _rmtmp(void)
1667 {
1668 int num_removed = 0, i;
1669
1670 LOCK_FILES();
1671 for (i = 3; i < stream_idx; i++)
1672 if (fstreams[i] && fstreams[i]->_tmpfname)
1673 {
1674 fclose(fstreams[i]);
1675 num_removed++;
1676 }
1677 UNLOCK_FILES();
1678
1679 if (num_removed)
1680 TRACE(":removed (%d) temp files\n",num_removed);
1681 return num_removed;
1682 }
1683
1684 /*********************************************************************
1685 * (internal) remove_cr
1686 *
1687 * Translate all \r\n to \n inplace.
1688 * return the number of \r removed
1689 * Corner cases required by some apps:
1690 * \r\r\n -> \r\n
1691 * BUG: should save state across calls somehow, so CR LF that
1692 * straddles buffer boundary gets recognized properly?
1693 */
1694 static unsigned int remove_cr(char *buf, unsigned int count)
1695 {
1696 unsigned int i, j;
1697
1698 for (i=0, j=0; j < count; j++)
1699 if ((buf[j] != '\r') || ((j+1) < count && buf[j+1] != '\n'))
1700 buf[i++] = buf[j];
1701
1702 return count - i;
1703 }
1704
1705 /*********************************************************************
1706 * (internal) read_i
1707 */
1708 static int read_i(int fd, void *buf, unsigned int count)
1709 {
1710 DWORD num_read;
1711 char *bufstart = buf;
1712 HANDLE hand = fdtoh(fd);
1713
1714 if (fdesc[fd].wxflag & WX_READEOF) {
1715 fdesc[fd].wxflag |= WX_ATEOF;
1716 TRACE("already at EOF, returning 0\n");
1717 return 0;
1718 }
1719 /* Don't trace small reads, it gets *very* annoying */
1720 if (count > 4)
1721 TRACE(":fd (%d) handle (%p) buf (%p) len (%d)\n",fd,hand,buf,count);
1722 if (hand == INVALID_HANDLE_VALUE)
1723 return -1;
1724
1725 /* Reading single bytes in O_TEXT mode makes things slow
1726 * So read big chunks
1727 */
1728 if (ReadFile(hand, bufstart, count, &num_read, NULL))
1729 {
1730 if (fdesc[fd].wxflag & WX_TEXT)
1731 {
1732 int i;
1733 /* in text mode, a ctrl-z signals EOF */
1734 for (i=0; i<num_read; i++)
1735 {
1736 if (bufstart[i] == 0x1a)
1737 {
1738 num_read = i;
1739 fdesc[fd].wxflag |= (WX_ATEOF|WX_READEOF);
1740 TRACE(":^Z EOF %s\n",debugstr_an(buf,num_read));
1741 break;
1742 }
1743 }
1744 }
1745 if (count != 0 && num_read == 0)
1746 {
1747 fdesc[fd].wxflag |= (WX_ATEOF|WX_READEOF);
1748 TRACE(":EOF %s\n",debugstr_an(buf,num_read));
1749 }
1750 }
1751 else
1752 {
1753 if (GetLastError() == ERROR_BROKEN_PIPE)
1754 {
1755 TRACE(":end-of-pipe\n");
1756 fdesc[fd].wxflag |= (WX_ATEOF|WX_READEOF);
1757 return 0;
1758 }
1759 else
1760 {
1761 TRACE(":failed-last error (%d)\n",GetLastError());
1762 return -1;
1763 }
1764 }
1765
1766 if (count > 4)
1767 TRACE("(%u), %s\n",num_read,debugstr_an(buf, num_read));
1768 return num_read;
1769 }
1770
1771 /*********************************************************************
1772 * _read (MSVCRT.@)
1773 */
1774 int CDECL _read(int fd, void *buf, unsigned int count)
1775 {
1776 int num_read;
1777 num_read = read_i(fd, buf, count);
1778 if (num_read>0 && fdesc[fd].wxflag & WX_TEXT)
1779 {
1780 num_read -= remove_cr(buf,num_read);
1781 }
1782 return num_read;
1783 }
1784
1785 /*********************************************************************
1786 * _setmode (MSVCRT.@)
1787 */
1788 int CDECL _setmode(int fd,int mode)
1789 {
1790 int ret = fdesc[fd].wxflag & WX_TEXT ? _O_TEXT : _O_BINARY;
1791 if (mode & (~(_O_TEXT|_O_BINARY)))
1792 FIXME("fd (%d) mode (0x%08x) unknown\n",fd,mode);
1793 if ((mode & _O_TEXT) == _O_TEXT)
1794 fdesc[fd].wxflag |= WX_TEXT;
1795 else
1796 fdesc[fd].wxflag &= ~WX_TEXT;
1797 return ret;
1798 }
1799
1800 /*********************************************************************
1801 * _stat64 (MSVCRT.@)
1802 */
1803 int CDECL _stat64(const char* path, struct __stat64 * buf)
1804 {
1805 DWORD dw;
1806 WIN32_FILE_ATTRIBUTE_DATA hfi;
1807 unsigned short mode = ALL_S_IREAD;
1808 int plen;
1809
1810 TRACE(":file (%s) buf(%p)\n",path,buf);
1811
1812 if (!GetFileAttributesExA(path, GetFileExInfoStandard, &hfi))
1813 {
1814 TRACE("failed (%d)\n",GetLastError());
1815 __set_errno(ERROR_FILE_NOT_FOUND);
1816 return -1;
1817 }
1818
1819 memset(buf,0,sizeof(struct __stat64));
1820
1821 /* FIXME: rdev isn't drive num, despite what the docs say-what is it?
1822 Bon 011120: This FIXME seems incorrect
1823 Also a letter as first char isn't enough to be classified
1824 as a drive letter
1825 */
1826 if (isalpha(*path)&& (*(path+1)==':'))
1827 buf->st_dev = buf->st_rdev = toupper(*path) - 'A'; /* drive num */
1828 else
1829 buf->st_dev = buf->st_rdev = _getdrive() - 1;
1830
1831 plen = strlen(path);
1832
1833 /* Dir, or regular file? */
1834 if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1835 (path[plen-1] == '\\'))
1836 mode |= (_S_IFDIR | ALL_S_IEXEC);
1837 else
1838 {
1839 mode |= _S_IFREG;
1840 /* executable? */
1841 if (plen > 6 && path[plen-4] == '.') /* shortest exe: "\x.exe" */
1842 {
1843 unsigned int ext = tolower(path[plen-1]) | (tolower(path[plen-2]) << 8) |
1844 (tolower(path[plen-3]) << 16);
1845 if (ext == EXE || ext == BAT || ext == CMD || ext == COM)
1846 mode |= ALL_S_IEXEC;
1847 }
1848 }
1849
1850 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1851 mode |= ALL_S_IWRITE;
1852
1853 buf->st_mode = mode;
1854 buf->st_nlink = 1;
1855 buf->st_size = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
1856 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
1857 buf->st_atime = dw;
1858 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
1859 buf->st_mtime = buf->st_ctime = dw;
1860 TRACE("%d %d 0x%08lx%08lx %ld %ld %ld\n", buf->st_mode,buf->st_nlink,
1861 (long)(buf->st_size >> 32),(long)buf->st_size,
1862 (long)buf->st_atime,(long)buf->st_mtime,(long)buf->st_ctime);
1863 return 0;
1864 }
1865
1866 /*********************************************************************
1867 * _stati64 (MSVCRT.@)
1868 */
1869 int CDECL _stati64(const char* path, struct _stati64 * buf)
1870 {
1871 int ret;
1872 struct __stat64 buf64;
1873
1874 ret = _stat64(path, &buf64);
1875 if (!ret)
1876 stat64_to_stati64(&buf64, buf);
1877 return ret;
1878 }
1879
1880 /*********************************************************************
1881 * _stat (MSVCRT.@)
1882 */
1883 int CDECL _stat(const char* path, struct _stat * buf)
1884 { int ret;
1885 struct __stat64 buf64;
1886
1887 ret = _stat64( path, &buf64);
1888 if (!ret)
1889 stat64_to_stat(&buf64, buf);
1890 return ret;
1891 }
1892
1893 /*********************************************************************
1894 * _wstat64 (MSVCRT.@)
1895 */
1896 int CDECL _wstat64(const wchar_t* path, struct __stat64 * buf)
1897 {
1898 DWORD dw;
1899 WIN32_FILE_ATTRIBUTE_DATA hfi;
1900 unsigned short mode = ALL_S_IREAD;
1901 int plen;
1902
1903 TRACE(":file (%s) buf(%p)\n",debugstr_w(path),buf);
1904
1905 if (!GetFileAttributesExW(path, GetFileExInfoStandard, &hfi))
1906 {
1907 TRACE("failed (%d)\n",GetLastError());
1908 __set_errno(ERROR_FILE_NOT_FOUND);
1909 return -1;
1910 }
1911
1912 memset(buf,0,sizeof(struct __stat64));
1913
1914 /* FIXME: rdev isn't drive num, despite what the docs says-what is it? */
1915 if (iswalpha(*path))
1916 buf->st_dev = buf->st_rdev = toupperW(*path - 'A'); /* drive num */
1917 else
1918 buf->st_dev = buf->st_rdev = _getdrive() - 1;
1919
1920 plen = strlenW(path);
1921
1922 /* Dir, or regular file? */
1923 if ((hfi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
1924 (path[plen-1] == '\\'))
1925 mode |= (_S_IFDIR | ALL_S_IEXEC);
1926 else
1927 {
1928 mode |= _S_IFREG;
1929 /* executable? */
1930 if (plen > 6 && path[plen-4] == '.') /* shortest exe: "\x.exe" */
1931 {
1932 ULONGLONG ext = tolowerW(path[plen-1]) | (tolowerW(path[plen-2]) << 16) |
1933 ((ULONGLONG)tolowerW(path[plen-3]) << 32);
1934 if (ext == WCEXE || ext == WCBAT || ext == WCCMD || ext == WCCOM)
1935 mode |= ALL_S_IEXEC;
1936 }
1937 }
1938
1939 if (!(hfi.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
1940 mode |= ALL_S_IWRITE;
1941
1942 buf->st_mode = mode;
1943 buf->st_nlink = 1;
1944 buf->st_size = ((__int64)hfi.nFileSizeHigh << 32) + hfi.nFileSizeLow;
1945 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastAccessTime, &dw);
1946 buf->st_atime = dw;
1947 RtlTimeToSecondsSince1970((LARGE_INTEGER *)&hfi.ftLastWriteTime, &dw);
1948 buf->st_mtime = buf->st_ctime = dw;
1949 TRACE("%d %d 0x%08lx%08lx %ld %ld %ld\n", buf->st_mode,buf->st_nlink,
1950 (long)(buf->st_size >> 32),(long)buf->st_size,
1951 (long)buf->st_atime,(long)buf->st_mtime,(long)buf->st_ctime);
1952 return 0;
1953 }
1954
1955 /*********************************************************************
1956 * _wstati64 (MSVCRT.@)
1957 */
1958 int CDECL _wstati64(const wchar_t* path, struct _stati64 * buf)
1959 {
1960 int ret;
1961 struct __stat64 buf64;
1962
1963 ret = _wstat64(path, &buf64);
1964 if (!ret)
1965 stat64_to_stati64(&buf64, buf);
1966 return ret;
1967 }
1968
1969 /*********************************************************************
1970 * _wstat (MSVCRT.@)
1971 */
1972 int CDECL _wstat(const wchar_t* path, struct _stat * buf)
1973 {
1974 int ret;
1975 struct __stat64 buf64;
1976
1977 ret = _wstat64( path, &buf64 );
1978 if (!ret) stat64_to_stat(&buf64, buf);
1979 return ret;
1980 }
1981
1982 /*********************************************************************
1983 * _tell (MSVCRT.@)
1984 */
1985 long CDECL _tell(int fd)
1986 {
1987 return _lseek(fd, 0, SEEK_CUR);
1988 }
1989
1990 /*********************************************************************
1991 * _telli64 (MSVCRT.@)
1992 */
1993 __int64 CDECL _telli64(int fd)
1994 {
1995 return _lseeki64(fd, 0, SEEK_CUR);
1996 }
1997
1998 /*********************************************************************
1999 * _tempnam (MSVCRT.@)
2000 */
2001 char * CDECL _tempnam(const char *dir, const char *prefix)
2002 {
2003 char tmpbuf[MAX_PATH];
2004 const char *tmp_dir = getenv("TMP");
2005
2006 if (tmp_dir) dir = tmp_dir;
2007
2008 TRACE("dir (%s) prefix (%s)\n",dir,prefix);
2009 if (GetTempFileNameA(dir,prefix,0,tmpbuf))
2010 {
2011 TRACE("got name (%s)\n",tmpbuf);
2012 DeleteFileA(tmpbuf);
2013 return _strdup(tmpbuf);
2014 }
2015 TRACE("failed (%d)\n",GetLastError());
2016 return NULL;
2017 }
2018
2019 /*********************************************************************
2020 * _wtempnam (MSVCRT.@)
2021 */
2022 wchar_t * CDECL _wtempnam(const wchar_t *dir, const wchar_t *prefix)
2023 {
2024 wchar_t tmpbuf[MAX_PATH];
2025
2026 TRACE("dir (%s) prefix (%s)\n",debugstr_w(dir),debugstr_w(prefix));
2027 if (GetTempFileNameW(dir,prefix,0,tmpbuf))
2028 {
2029 TRACE("got name (%s)\n",debugstr_w(tmpbuf));
2030 DeleteFileW(tmpbuf);
2031 return _wcsdup(tmpbuf);
2032 }
2033 TRACE("failed (%d)\n",GetLastError());
2034 return NULL;
2035 }
2036
2037 /*********************************************************************
2038 * _umask (MSVCRT.@)
2039 */
2040 int CDECL _umask(int umask)
2041 {
2042 int old_umask = umask;
2043 TRACE("(%d)\n",umask);
2044 MSVCRT_umask = umask;
2045 return old_umask;
2046 }
2047
2048 /*********************************************************************
2049 * _utime (MSVCRT.@)
2050 */
2051 int CDECL _utime(const char* path, struct _utimbuf *t)
2052 {
2053 int fd = _open(path, _O_WRONLY | _O_BINARY);
2054
2055 if (fd > 0)
2056 {
2057 int retVal = _futime(fd, t);
2058 _close(fd);
2059 return retVal;
2060 }
2061 return -1;
2062 }
2063
2064 /*********************************************************************
2065 * _wutime (MSVCRT.@)
2066 */
2067 int CDECL _wutime(const wchar_t* path, struct _utimbuf *t)
2068 {
2069 int fd = _wopen(path, _O_WRONLY | _O_BINARY);
2070
2071 if (fd > 0)
2072 {
2073 int retVal = _futime(fd, t);
2074 _close(fd);
2075 return retVal;
2076 }
2077 return -1;
2078 }
2079
2080 /*********************************************************************
2081 * _write (MSVCRT.@)
2082 */
2083 int CDECL _write(int fd, const void* buf, unsigned int count)
2084 {
2085 DWORD num_written;
2086 HANDLE hand = fdtoh(fd);
2087
2088 /* Don't trace small writes, it gets *very* annoying */
2089 #if 0
2090 if (count > 32)
2091 TRACE(":fd (%d) handle (%d) buf (%p) len (%d)\n",fd,hand,buf,count);
2092 #endif
2093 if (hand == INVALID_HANDLE_VALUE)
2094 {
2095 *_errno() = EBADF;
2096 return -1;
2097 }
2098
2099 /* If appending, go to EOF */
2100 if (fdesc[fd].wxflag & WX_APPEND)
2101 _lseek(fd, 0, FILE_END);
2102
2103 if (!(fdesc[fd].wxflag & WX_TEXT))
2104 {
2105 if (WriteFile(hand, buf, count, &num_written, NULL)
2106 && (num_written == count))
2107 return num_written;
2108 TRACE("WriteFile (fd %d, hand %p) failed-last error (%d)\n", fd,
2109 hand, GetLastError());
2110 *_errno() = ENOSPC;
2111 }
2112 else
2113 {
2114 unsigned int i, j, nr_lf;
2115 char *p = NULL;
2116 const char *q;
2117 const char *s = (const char *)buf, *buf_start = (const char *)buf;
2118 /* find number of \n ( without preceding \r ) */
2119 for ( nr_lf=0,i = 0; i <count; i++)
2120 {
2121 if (s[i]== '\n')
2122 {
2123 nr_lf++;
2124 /*if ((i >1) && (s[i-1] == '\r')) nr_lf--; */
2125 }
2126 }
2127 if (nr_lf)
2128 {
2129 if ((q = p = malloc(count + nr_lf)))
2130 {
2131 for (s = (const char *)buf, i = 0, j = 0; i < count; i++)
2132 {
2133 if (s[i]== '\n')
2134 {
2135 p[j++] = '\r';
2136 /*if ((i >1) && (s[i-1] == '\r'))j--;*/
2137 }
2138 p[j++] = s[i];
2139 }
2140 }
2141 else
2142 {
2143 FIXME("Malloc failed\n");
2144 nr_lf =0;
2145 q = buf;
2146 }
2147 }
2148 else
2149 q = buf;
2150
2151 if ((WriteFile(hand, q, count+nr_lf, &num_written, NULL) == 0 ) || (num_written != count+nr_lf))
2152 {
2153 TRACE("WriteFile (fd %d, hand %p) failed-last error (%d), num_written %d\n",
2154 fd, hand, GetLastError(), num_written);
2155 *_errno() = ENOSPC;
2156 if(nr_lf)
2157 free(p);
2158 return s - buf_start;
2159 }
2160 else
2161 {
2162 if(nr_lf)
2163 free(p);
2164 return count;
2165 }
2166 }
2167 return -1;
2168 }
2169
2170 /*********************************************************************
2171 * _putw (MSVCRT.@)
2172 */
2173 int CDECL _putw(int val, FILE* file)
2174 {
2175 int len;
2176 len = _write(file->_file, &val, sizeof(val));
2177 if (len == sizeof(val)) return val;
2178 file->_flag |= _IOERR;
2179 return EOF;
2180 }
2181
2182 /*********************************************************************
2183 * fclose (MSVCRT.@)
2184 */
2185 int CDECL fclose(FILE* file)
2186 {
2187 int r, flag;
2188
2189 flag = file->_flag;
2190 free(file->_tmpfname);
2191 file->_tmpfname = NULL;
2192 /* flush stdio buffers */
2193 if(file->_flag & _IOWRT)
2194 fflush(file);
2195 if(file->_flag & _IOMYBUF)
2196 free(file->_base);
2197
2198 r=_close(file->_file);
2199
2200 file->_flag = 0;
2201
2202 return ((r == -1) || (flag & _IOERR) ? EOF : 0);
2203 }
2204
2205 /*********************************************************************
2206 * feof (MSVCRT.@)
2207 */
2208 int CDECL feof(FILE* file)
2209 {
2210 return file->_flag & _IOEOF;
2211 }
2212
2213 /*********************************************************************
2214 * ferror (MSVCRT.@)
2215 */
2216 int CDECL ferror(FILE* file)
2217 {
2218 return file->_flag & _IOERR;
2219 }
2220
2221 /*********************************************************************
2222 * _filbuf (MSVCRT.@)
2223 */
2224 int CDECL _filbuf(FILE* file)
2225 {
2226 /* Allocate buffer if needed */
2227 if(file->_bufsiz == 0 && !(file->_flag & _IONBF) ) {
2228 alloc_buffer(file);
2229 }
2230 if(!(file->_flag & _IOREAD)) {
2231 if(file->_flag & _IORW) {
2232 file->_flag |= _IOREAD;
2233 } else {
2234 return EOF;
2235 }
2236 }
2237 if(file->_flag & _IONBF) {
2238 unsigned char c;
2239 int r;
2240 if ((r = read_i(file->_file,&c,1)) != 1) {
2241 file->_flag |= (r == 0) ? _IOEOF : _IOERR;
2242 return EOF;
2243 }
2244 return c;
2245 } else {
2246 file->_cnt = read_i(file->_file, file->_base, file->_bufsiz);
2247 if(file->_cnt<=0) {
2248 file->_flag |= (file->_cnt == 0) ? _IOEOF : _IOERR;
2249 file->_cnt = 0;
2250 return EOF;
2251 }
2252 file->_cnt--;
2253 file->_ptr = file->_base+1;
2254 return *(unsigned char *)file->_base;
2255 }
2256 }
2257
2258 /*********************************************************************
2259 * fgetc (MSVCRT.@)
2260 */
2261 int CDECL fgetc(FILE* file)
2262 {
2263 unsigned char *i;
2264 unsigned int j;
2265 do {
2266 if (file->_cnt>0) {
2267 file->_cnt--;
2268 i = (unsigned char *)file->_ptr++;
2269 j = *i;
2270 } else
2271 j = _filbuf(file);
2272 if (!(fdesc[file->_file].wxflag & WX_TEXT)
2273 || ((j != '\r') || (file->_cnt && file->_ptr[0] != '\n')))
2274 return j;
2275 } while(1);
2276 }
2277
2278 /*********************************************************************
2279 * _fgetchar (MSVCRT.@)
2280 */
2281 int CDECL _fgetchar(void)
2282 {
2283 return fgetc(stdin);
2284 }
2285
2286 /*********************************************************************
2287 * fgets (MSVCRT.@)
2288 */
2289 char * CDECL fgets(char *s, int size, FILE* file)
2290 {
2291 int cc = EOF;
2292 char * buf_start = s;
2293
2294 TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
2295 file,file->_file,s,size);
2296
2297 while ((size >1) && (cc = fgetc(file)) != EOF && cc != '\n')
2298 {
2299 *s++ = (char)cc;
2300 size --;
2301 }
2302 if ((cc == EOF) && (s == buf_start)) /* If nothing read, return 0*/
2303 {
2304 TRACE(":nothing read\n");
2305 return NULL;
2306 }
2307 if ((cc != EOF) && (size > 1))
2308 *s++ = cc;
2309 *s = '\0';
2310 TRACE(":got %s\n", debugstr_a(buf_start));
2311 return buf_start;
2312 }
2313
2314 /*********************************************************************
2315 * fgetwc (MSVCRT.@)
2316 *
2317 * In _O_TEXT mode, multibyte characters are read from the file, dropping
2318 * the CR from CR/LF combinations
2319 */
2320 wint_t CDECL fgetwc(FILE* file)
2321 {
2322 char c;
2323
2324 if (!(fdesc[file->_file].wxflag & WX_TEXT))
2325 {
2326 wchar_t wc;
2327 int i,j;
2328 char *chp, *wcp;
2329 wcp = (char *)&wc;
2330 for(i=0; i<sizeof(wc); i++)
2331 {
2332 if (file->_cnt>0)
2333 {
2334 file->_cnt--;
2335 chp = file->_ptr++;
2336 wcp[i] = *chp;
2337 }
2338 else
2339 {
2340 j = _filbuf(file);
2341 if(file->_cnt<=0)
2342 {
2343 file->_flag |= (file->_cnt == 0) ? _IOEOF : _IOERR;
2344 file->_cnt = 0;
2345 return WEOF;
2346 }
2347 wcp[i] = j;
2348 }
2349 }
2350 return wc;
2351 }
2352
2353 c = fgetc(file);
2354 if ((*__p___mb_cur_max() > 1) && isleadbyte(c))
2355 {
2356 FIXME("Treat Multibyte characters\n");
2357 }
2358 if (c == EOF)
2359 return WEOF;
2360 else
2361 return (wint_t)c;
2362 }
2363
2364 /*********************************************************************
2365 * _getw (MSVCRT.@)
2366 */
2367 int CDECL _getw(FILE* file)
2368 {
2369 char *ch;
2370 int i, j, k;
2371 ch = (char *)&i;
2372 for (j=0; j<sizeof(int); j++) {
2373 k = fgetc(file);
2374 if (k == EOF) {
2375 file->_flag |= _IOEOF;
2376 return EOF;
2377 }
2378 ch[j] = k;
2379 }
2380 return i;
2381 }
2382
2383 /*********************************************************************
2384 * getwc (MSVCRT.@)
2385 */
2386 wint_t CDECL getwc(FILE* file)
2387 {
2388 return fgetwc(file);
2389 }
2390
2391 /*********************************************************************
2392 * _fgetwchar (MSVCRT.@)
2393 */
2394 wint_t CDECL _fgetwchar(void)
2395 {
2396 return fgetwc(stdin);
2397 }
2398
2399 /*********************************************************************
2400 * getwchar (MSVCRT.@)
2401 */
2402 wint_t CDECL getwchar(void)
2403 {
2404 return _fgetwchar();
2405 }
2406
2407 /*********************************************************************
2408 * fgetws (MSVCRT.@)
2409 */
2410 wchar_t * CDECL fgetws(wchar_t *s, int size, FILE* file)
2411 {
2412 int cc = WEOF;
2413 wchar_t * buf_start = s;
2414
2415 TRACE(":file(%p) fd (%d) str (%p) len (%d)\n",
2416 file,file->_file,s,size);
2417
2418 while ((size >1) && (cc = fgetwc(file)) != WEOF && cc != '\n')
2419 {
2420 *s++ = (char)cc;
2421 size --;
2422 }
2423 if ((cc == WEOF) && (s == buf_start)) /* If nothing read, return 0*/
2424 {
2425 TRACE(":nothing read\n");
2426 return NULL;
2427 }
2428 if ((cc != WEOF) && (size > 1))
2429 *s++ = cc;
2430 *s = 0;
2431 TRACE(":got %s\n", debugstr_w(buf_start));
2432 return buf_start;
2433 }
2434
2435 /*********************************************************************
2436 * fwrite (MSVCRT.@)
2437 */
2438 size_t CDECL fwrite(const void *ptr, size_t size, size_t nmemb, FILE* file)
2439 {
2440 size_t wrcnt=size * nmemb;
2441 int written = 0;
2442 if (size == 0)
2443 return 0;
2444 if(file->_cnt) {
2445 int pcnt=(file->_cnt>wrcnt)? wrcnt: file->_cnt;
2446 memcpy(file->_ptr, ptr, pcnt);
2447 file->_cnt -= pcnt;
2448 file->_ptr += pcnt;
2449 written = pcnt;
2450 wrcnt -= pcnt;
2451 ptr = (const char*)ptr + pcnt;
2452 } else if(!(file->_flag & _IOWRT)) {
2453 if(file->_flag & _IORW) {
2454 file->_flag |= _IOWRT;
2455 } else
2456 return 0;
2457 }
2458 if(wrcnt) {
2459 /* Flush buffer */
2460 int res=flush_buffer(file);
2461 if(!res) {
2462 int pwritten = _write(file->_file, ptr, wrcnt);
2463 if (pwritten <= 0)
2464 {
2465 file->_flag |= _IOERR;
2466 pwritten=0;
2467 }
2468 written += pwritten;
2469 }
2470 }
2471 return written / size;
2472 }
2473
2474 /*********************************************************************
2475 * fputwc (MSVCRT.@)
2476 */
2477 wint_t CDECL fputwc(wint_t wc, FILE* file)
2478 {
2479 if (file->_flag & _IOBINARY)
2480 {
2481 if (fwrite(&wc, sizeof(wc), 1, file) != 1)
2482 return WEOF;
2483 }
2484 else
2485 {
2486 /* Convert to multibyte in text mode */
2487 char mbc[MB_LEN_MAX];
2488 int mb_return;
2489
2490 mb_return = wctomb(mbc, wc);
2491
2492 if(mb_return == -1)
2493 return WEOF;
2494
2495 /* Output all characters */
2496 if (fwrite(mbc, mb_return, 1, file) != 1)
2497 return WEOF;
2498 }
2499
2500 return wc;
2501 }
2502
2503 /*********************************************************************
2504 * _fputwchar (MSVCRT.@)
2505 */
2506 wint_t CDECL _fputwchar(wint_t wc)
2507 {
2508 return fputwc(wc, stdout);
2509 }
2510
2511 /*********************************************************************
2512 * _fsopen (MSVCRT.@)
2513 */
2514 FILE * CDECL _fsopen(const char *path, const char *mode, int share)
2515 {
2516 FILE* file;
2517 int open_flags, stream_flags, fd;
2518
2519 TRACE("(%s,%s)\n",path,mode);
2520
2521 /* map mode string to open() flags. "man fopen" for possibilities. */
2522 if (get_flags(mode, &open_flags, &stream_flags) == -1)
2523 return NULL;
2524
2525 LOCK_FILES();
2526 fd = _sopen(path, open_flags, share, _S_IREAD | _S_IWRITE);
2527 if (fd < 0)
2528 file = NULL;
2529 else if ((file = alloc_fp()) && init_fp(file, fd, stream_flags)
2530 != -1)
2531 TRACE(":fd (%d) mode (%s) FILE* (%p)\n",fd,mode,file);
2532 else if (file)
2533 {
2534 file->_flag = 0;
2535 file = NULL;
2536 }
2537
2538 TRACE(":got (%p)\n",file);
2539 if (fd >= 0 && !file)
2540 _close(fd);
2541 UNLOCK_FILES();
2542 return file;
2543 }
2544
2545 /*********************************************************************
2546 * _wfsopen (MSVCRT.@)
2547 */
2548 FILE * CDECL _wfsopen(const wchar_t *path, const wchar_t *mode, int share)
2549 {
2550 const unsigned int plen = strlenW(path), mlen = strlenW(mode);
2551 char *patha = calloc(plen + 1, 1);
2552 char *modea = calloc(mlen + 1, 1);
2553
2554 TRACE("(%s,%s)\n",debugstr_w(path),debugstr_w(mode));
2555
2556 if (patha && modea &&
2557 WideCharToMultiByte(CP_ACP,0,path,plen,patha,plen,NULL,NULL) &&
2558 WideCharToMultiByte(CP_ACP,0,mode,mlen,modea,mlen,NULL,NULL))
2559 {
2560 FILE *retval = _fsopen(patha,modea,share);
2561 free(patha);
2562 free(modea);
2563 return retval;
2564 }
2565 free(patha);
2566 free(modea);
2567 __set_errno(GetLastError());
2568 return NULL;
2569 }
2570
2571 /*********************************************************************
2572 * fopen (MSVCRT.@)
2573 */
2574 FILE * CDECL fopen(const char *path, const char *mode)
2575 {
2576 return _fsopen( path, mode, _SH_DENYNO );
2577 }
2578
2579 /*********************************************************************
2580 * _wfopen (MSVCRT.@)
2581 */
2582 FILE * CDECL _wfopen(const wchar_t *path, const wchar_t *mode)
2583 {
2584 return _wfsopen( path, mode, _SH_DENYNO );
2585 }
2586
2587 /* fputc calls _flsbuf which calls fputc */
2588 int CDECL _flsbuf(int c, FILE* file);
2589
2590 /*********************************************************************
2591 * fputc (MSVCRT.@)
2592 */
2593 int CDECL fputc(int c, FILE* file)
2594 {
2595 if(file->_cnt>0) {
2596 *file->_ptr++=c;
2597 file->_cnt--;
2598 if (c == '\n')
2599 {
2600 int res = flush_buffer(file);
2601 return res ? res : c;
2602 }
2603 else
2604 return c;
2605 } else {
2606 return _flsbuf(c, file);
2607 }
2608 }
2609
2610 /*********************************************************************
2611 * _flsbuf (MSVCRT.@)
2612 */
2613 int CDECL _flsbuf(int c, FILE* file)
2614 {
2615 /* Flush output buffer */
2616 if(file->_bufsiz == 0 && !(file->_flag & _IONBF)) {
2617 alloc_buffer(file);
2618 }
2619 if(!(file->_flag & _IOWRT)) {
2620 if(file->_flag & _IORW) {
2621 file->_flag |= _IOWRT;
2622 } else {
2623 return EOF;
2624 }
2625 }
2626 if(file->_bufsiz) {
2627 int res=flush_buffer(file);
2628 return res?res : fputc(c, file);
2629 } else {
2630 unsigned char cc=c;
2631 int len;
2632 len = _write(file->_file, &cc, 1);
2633 if (len == 1) return c;
2634 file->_flag |= _IOERR;
2635 return EOF;
2636 }
2637 }
2638
2639 /*********************************************************************
2640 * _fputchar (MSVCRT.@)
2641 */
2642 int CDECL _fputchar(int c)
2643 {
2644 return fputc(c, stdout);
2645 }
2646
2647 /*********************************************************************
2648 * fread (MSVCRT.@)
2649 */
2650 size_t CDECL fread(void *ptr, size_t size, size_t nmemb, FILE* file)
2651 { size_t rcnt=size * nmemb;
2652 size_t read=0;
2653 int pread=0;
2654
2655 if(!rcnt)
2656 return 0;
2657
2658 /* first buffered data */
2659 if(file->_cnt>0) {
2660 int pcnt= (rcnt>file->_cnt)? file->_cnt:rcnt;
2661 memcpy(ptr, file->_ptr, pcnt);
2662 file->_cnt -= pcnt;
2663 file->_ptr += pcnt;
2664 if (fdesc[file->_file].wxflag & WX_TEXT)
2665 pcnt -= remove_cr(ptr,pcnt);
2666 read += pcnt ;
2667 rcnt -= pcnt ;
2668 ptr = (char*)ptr + pcnt;
2669 } else if(!(file->_flag & _IOREAD )) {
2670 if(file->_flag & _IORW) {
2671 file->_flag |= _IOREAD;
2672 } else
2673 return 0;
2674 }
2675 while(rcnt>0)
2676 {
2677 int i;
2678 /* Fill the buffer on small reads.
2679 * TODO: Use a better buffering strategy.
2680 */
2681 if (!file->_cnt && size*nmemb <= BUFSIZ/2 && !(file->_flag & _IONBF)) {
2682 if (file->_bufsiz == 0) {
2683 alloc_buffer(file);
2684 }
2685 file->_cnt = _read(file->_file, file->_base, file->_bufsiz);
2686 file->_ptr = file->_base;
2687 i = (file->_cnt<rcnt) ? file->_cnt : rcnt;
2688 /* If the buffer fill reaches eof but fread wouldn't, clear eof. */
2689 if (i > 0 && i < file->_cnt) {
2690 fdesc[file->_file].wxflag &= ~WX_ATEOF;
2691 file->_flag &= ~_IOEOF;
2692 }
2693 if (i > 0) {
2694 memcpy(ptr, file->_ptr, i);
2695 file->_cnt -= i;
2696 file->_ptr += i;
2697 }
2698 } else {
2699 i = _read(file->_file,ptr, rcnt);
2700 }
2701 pread += i;
2702 rcnt -= i;
2703 ptr = (char *)ptr+i;
2704 /* expose feof condition in the flags
2705 * MFC tests file->_flag for feof, and doesn't call feof())
2706 */
2707 if ( fdesc[file->_file].wxflag & WX_ATEOF)
2708 file->_flag |= _IOEOF;
2709 else if (i == -1)
2710 {
2711 file->_flag |= _IOERR;
2712 pread = 0;
2713 rcnt = 0;
2714 }
2715 if (i < 1) break;
2716 }
2717 read+=pread;
2718 return read / size;
2719 }
2720
2721 /*********************************************************************
2722 * freopen (MSVCRT.@)
2723 *
2724 */
2725 FILE* CDECL freopen(const char *path, const char *mode,FILE* file)
2726 {
2727 int open_flags, stream_flags, fd;
2728
2729 TRACE(":path (%p) mode (%s) file (%p) fd (%d)\n",path,mode,file,file->_file);
2730
2731 LOCK_FILES();
2732 if (!file || ((fd = file->_file) < 0) || fd > fdend)
2733 file = NULL;
2734 else
2735 {
2736 fclose(file);
2737 /* map mode string to open() flags. "man fopen" for possibilities. */
2738 if (get_flags(mode, &open_flags, &stream_flags) == -1)
2739 file = NULL;
2740 else
2741 {
2742 fd = _open(path, open_flags, _S_IREAD | _S_IWRITE);
2743 if (fd < 0)
2744 file = NULL;
2745 else if (init_fp(file, fd, stream_flags) == -1)
2746 {
2747 file->_flag = 0;
2748 WARN(":failed-last error (%d)\n",GetLastError());
2749 __set_errno(GetLastError());
2750 file = NULL;
2751 }
2752 }
2753 }
2754 UNLOCK_FILES();
2755 return file;
2756 }
2757
2758 /*********************************************************************
2759 * wfreopen (MSVCRT.@)
2760 *
2761 */
2762 FILE* CDECL _wfreopen(const wchar_t *path, const wchar_t *mode,FILE* file)
2763 {
2764 FIXME("UNIMPLEMENTED stub!\n");
2765 return NULL;
2766 }
2767
2768 /*********************************************************************
2769 * fsetpos (MSVCRT.@)
2770 */
2771 int CDECL fsetpos(FILE* file, const fpos_t *pos)
2772 {
2773 /* Note that all this has been lifted 'as is' from fseek */
2774 if(file->_flag & _IOWRT)
2775 flush_buffer(file);
2776
2777 /* Discard buffered input */
2778 file->_cnt = 0;
2779 file->_ptr = file->_base;
2780
2781 /* Reset direction of i/o */
2782 if(file->_flag & _IORW) {
2783 file->_flag &= ~(_IOREAD|_IOWRT);
2784 }
2785
2786 return (_lseeki64(file->_file,*pos,SEEK_SET) == -1) ? -1 : 0;
2787 }
2788
2789 /*********************************************************************
2790 * ftell (MSVCRT.@)
2791 */
2792 LONG CDECL ftell(FILE* file)
2793 {
2794 int off=0;
2795 long pos;
2796 if(file->_bufsiz) {
2797 if( file->_flag & _IOWRT ) {
2798 off = file->_ptr - file->_base;
2799 } else {
2800 off = -file->_cnt;
2801 }
2802 }
2803 pos = _tell(file->_file);
2804 if(pos == -1) return pos;
2805 return off + pos;
2806 }
2807
2808 /*********************************************************************
2809 * fgetpos (MSVCRT.@)
2810 */
2811 int CDECL fgetpos(FILE* file, fpos_t *pos)
2812 {
2813 /* This code has been lifted form the ftell function */
2814 int off=0;
2815
2816 *pos = _lseeki64(file->_file,0,SEEK_CUR);
2817
2818 if (*pos == -1) return -1;
2819
2820 if(file->_bufsiz) {
2821 if( file->_flag & _IOWRT ) {
2822 off = file->_ptr - file->_base;
2823 } else {
2824 off = -file->_cnt;
2825 }
2826 }
2827 *pos += off;
2828
2829 return 0;
2830 }
2831
2832 /*********************************************************************
2833 * fputs (MSVCRT.@)
2834 */
2835 int CDECL fputs(const char *s, FILE* file)
2836 {
2837 size_t i, len = strlen(s);
2838 if (!(fdesc[file->_file].wxflag & WX_TEXT))
2839 return fwrite(s,sizeof(*s),len,file) == len ? 0 : EOF;
2840 for (i=0; i<len; i++)
2841 if (fputc(s[i], file) == EOF)
2842 return EOF;
2843 return 0;
2844 }
2845
2846 /*********************************************************************
2847 * fputws (MSVCRT.@)
2848 */
2849 int CDECL fputws(const wchar_t *s, FILE* file)
2850 {
2851 size_t i, len = strlenW(s);
2852 if (!(fdesc[file->_file].wxflag & WX_TEXT))
2853 return fwrite(s,sizeof(*s),len,file) == len ? 0 : EOF;
2854 for (i=0; i<len; i++)
2855 {
2856 if ((s[i] == '\n') && (fputc('\r', file) == EOF))
2857 return WEOF;
2858 if (fputwc(s[i], file) == WEOF)
2859 return WEOF;
2860 }
2861 return 0;
2862 }
2863
2864 /*********************************************************************
2865 * getchar (MSVCRT.@)
2866 */
2867 int CDECL getchar(void)
2868 {
2869 return fgetc(stdin);
2870 }
2871
2872 /*********************************************************************
2873 * getc (MSVCRT.@)
2874 */
2875 int CDECL getc(FILE* file)
2876 {
2877 return fgetc(file);
2878 }
2879
2880 /*********************************************************************
2881 * gets (MSVCRT.@)
2882 */
2883 char * CDECL gets(char *buf)
2884 {
2885 int cc;
2886 char * buf_start = buf;
2887
2888 for(cc = fgetc(stdin); cc != EOF && cc != '\n';
2889 cc = fgetc(stdin))
2890 if(cc != '\r') *buf++ = (char)cc;
2891
2892 *buf = '\0';
2893
2894 TRACE("got '%s'\n", buf_start);
2895 return buf_start;
2896 }
2897
2898 /*********************************************************************
2899 * _getws (MSVCRT.@)
2900 */
2901 wchar_t* CDECL _getws(wchar_t* buf)
2902 {
2903 wint_t cc;
2904 wchar_t* ws = buf;
2905
2906 for (cc = fgetwc(stdin); cc != WEOF && cc != '\n';
2907 cc = fgetwc(stdin))
2908 {
2909 if (cc != '\r')
2910 *buf++ = (wchar_t)cc;
2911 }
2912 *buf = '\0';
2913
2914 TRACE("got %s\n", debugstr_w(ws));
2915 return ws;
2916 }
2917
2918 /*********************************************************************
2919 * putc (MSVCRT.@)
2920 */
2921 int CDECL putc(int c, FILE* file)
2922 {
2923 return fputc(c, file);
2924 }
2925
2926 /*********************************************************************
2927 * putchar (MSVCRT.@)
2928 */
2929 int CDECL putchar(int c)
2930 {
2931 return fputc(c, stdout);
2932 }
2933
2934 /*********************************************************************
2935 * puts (MSVCRT.@)
2936 */
2937 int CDECL puts(const char *s)
2938 {
2939 size_t len = strlen(s);
2940 if (fwrite(s,sizeof(*s),len,stdout) != len) return EOF;
2941 return fwrite("\n",1,1,stdout) == 1 ? 0 : EOF;
2942 }
2943
2944 /*********************************************************************
2945 * _putws (MSVCRT.@)
2946 */
2947 int CDECL _putws(const wchar_t *s)
2948 {
2949 static const wchar_t nl = '\n';
2950 size_t len = strlenW(s);
2951 if (fwrite(s,sizeof(*s),len,stdout) != len) return EOF;
2952 return fwrite(&nl,sizeof(nl),1,stdout) == 1 ? 0 : EOF;
2953 }
2954
2955 /*********************************************************************
2956 * remove (MSVCRT.@)
2957 */
2958 int CDECL remove(const char *path)
2959 {
2960 TRACE("(%s)\n",path);
2961 if (DeleteFileA(path))
2962 return 0;
2963 TRACE(":failed (%d)\n",GetLastError());
2964 __set_errno(GetLastError());
2965 return -1;
2966 }
2967
2968 /*********************************************************************
2969 * _wremove (MSVCRT.@)
2970 */
2971 int CDECL _wremove(const wchar_t *path)
2972 {
2973 TRACE("(%s)\n",debugstr_w(path));
2974 if (DeleteFileW(path))
2975 return 0;
2976 TRACE(":failed (%d)\n",GetLastError());
2977 __set_errno(GetLastError());
2978 return -1;
2979 }
2980
2981 /*********************************************************************
2982 * rename (MSVCRT.@)
2983 */
2984 int CDECL rename(const char *oldpath,const char *newpath)
2985 {
2986 TRACE(":from %s to %s\n",oldpath,newpath);
2987 if (MoveFileExA(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
2988 return 0;
2989 TRACE(":failed (%d)\n",GetLastError());
2990 __set_errno(GetLastError());
2991 return -1;
2992 }
2993
2994 /*********************************************************************
2995 * _wrename (MSVCRT.@)
2996 */
2997 int CDECL _wrename(const wchar_t *oldpath,const wchar_t *newpath)
2998 {
2999 TRACE(":from %s to %s\n",debugstr_w(oldpath),debugstr_w(newpath));
3000 if (MoveFileExW(oldpath, newpath, MOVEFILE_COPY_ALLOWED))
3001 return 0;
3002 TRACE(":failed (%d)\n",GetLastError());
3003 __set_errno(GetLastError());
3004 return -1;
3005 }
3006
3007 /*********************************************************************
3008 * setvbuf (MSVCRT.@)
3009 */
3010 int CDECL setvbuf(FILE* file, char *buf, int mode, size_t size)
3011 {
3012 /* TODO: Check if file busy */
3013 if(file->_bufsiz) {
3014 free(file->_base);
3015 file->_bufsiz = 0;
3016 file->_cnt = 0;
3017 }
3018 if(mode == _IOFBF) {
3019 file->_flag &= ~_IONBF;
3020 file->_base = file->_ptr = buf;
3021 if(buf) {
3022 file->_bufsiz = size;
3023 }
3024 } else {
3025 file->_flag |= _IONBF;
3026 }
3027 return 0;
3028 }
3029
3030 /*********************************************************************
3031 * setbuf (MSVCRT.@)
3032 */
3033 void CDECL setbuf(FILE* file, char *buf)
3034 {
3035 setvbuf(file, buf, buf ? _IOFBF : _IONBF, BUFSIZ);
3036 }
3037
3038 /*********************************************************************
3039 * tmpnam (MSVCRT.@)
3040 */
3041 char * CDECL tmpnam(char *s)
3042 {
3043 static int unique;
3044 char tmpstr[16];
3045 char *p;
3046 int count;
3047 if (s == 0)
3048 s = tmpname;
3049 int_to_base32(GetCurrentProcessId(), tmpstr);
3050 p = s + sprintf(s, "\\s%s.", tmpstr);
3051 for (count = 0; count < TMP_MAX; count++)
3052 {
3053 int_to_base32(unique++, tmpstr);
3054 strcpy(p, tmpstr);
3055 if (GetFileAttributesA(s) == INVALID_FILE_ATTRIBUTES &&
3056 GetLastError() == ERROR_FILE_NOT_FOUND)
3057 break;
3058 }
3059 return s;
3060 }
3061
3062 /*********************************************************************
3063 * wtmpnam (MSVCRT.@)
3064 */
3065 wchar_t * CDECL _wtmpnam(wchar_t *s)
3066 {
3067 ERR("UNIMPLEMENTED!\n");
3068 return NULL;
3069 }
3070
3071 /*********************************************************************
3072 * tmpfile (MSVCRT.@)
3073 */
3074 FILE* CDECL tmpfile(void)
3075 {
3076 char *filename = tmpnam(NULL);
3077 int fd;
3078 FILE* file = NULL;
3079
3080 LOCK_FILES();
3081 fd = _open(filename, _O_CREAT | _O_BINARY | _O_RDWR | _O_TEMPORARY);
3082 if (fd != -1 && (file = alloc_fp()))
3083 {
3084 if (init_fp(file, fd, _O_RDWR) == -1)
3085 {
3086 file->_flag = 0;
3087 file = NULL;
3088 }
3089 else file->_tmpfname = _strdup(filename);
3090 }
3091 UNLOCK_FILES();
3092 return file;
3093 }
3094
3095 /*********************************************************************
3096 * vfprintf (MSVCRT.@)
3097 */
3098 int CDECL vfprintf(FILE* file, const char *format, va_list valist)
3099 {
3100 char buf[2048], *mem = buf;
3101 int written, resize = sizeof(buf), retval;
3102 /* There are two conventions for vsnprintf failing:
3103 * Return -1 if we truncated, or
3104 * Return the number of bytes that would have been written
3105 * The code below handles both cases
3106 */
3107 while ((written = _vsnprintf(mem, resize, format, valist)) == -1 ||
3108 written > resize)
3109 {
3110 resize = (written == -1 ? resize * 2 : written + 1);
3111 if (mem != buf)
3112 free (mem);
3113 if (!(mem = malloc(resize)))
3114 return EOF;
3115 }
3116 retval = fwrite(mem, sizeof(*mem), written, file);
3117 if (mem != buf)
3118 free (mem);
3119 return retval;
3120 }
3121
3122 /*********************************************************************
3123 * vfwprintf (MSVCRT.@)
3124 * FIXME:
3125 * Is final char included in written (then resize is too big) or not
3126 * (then we must test for equality too)?
3127 */
3128 int CDECL vfwprintf(FILE* file, const wchar_t *format, va_list valist)
3129 {
3130 wchar_t buf[2048], *mem = buf;
3131 int written, resize = sizeof(buf) / sizeof(wchar_t), retval;
3132 /* See vfprintf comments */
3133 while ((written = _vsnwprintf(mem, resize, format, valist)) == -1 ||
3134 written > resize)
3135 {
3136 resize = (written == -1 ? resize * 2 : written + sizeof(wchar_t));
3137 if (mem != buf)
3138 free (mem);
3139 if (!(mem = malloc(resize*sizeof(*mem))))
3140 return EOF;
3141 }
3142
3143 /* Check if outputting to a text-file */
3144 if (fdesc[file->_file].wxflag & WX_TEXT)
3145 {
3146 /* Convert each character and stop at the first invalid character. Behavior verified by tests under WinXP SP2 */
3147 char chMultiByte[MB_LEN_MAX];
3148 int nReturn;
3149 wchar_t *p;
3150
3151 retval = 0;
3152
3153 for (p = mem; *p; p++)
3154 {
3155 nReturn = wctomb(chMultiByte, *p);
3156
3157 if(nReturn == -1)
3158 break;
3159
3160 retval += fwrite(chMultiByte, 1, nReturn, file);
3161 }
3162 }
3163 else
3164 {
3165 retval = fwrite(mem, sizeof(*mem), written, file);
3166 }
3167
3168 if (mem != buf)
3169 free (mem);
3170
3171 return retval;
3172 }
3173
3174 /*********************************************************************
3175 * vprintf (MSVCRT.@)
3176 */
3177 int CDECL vprintf(const char *format, va_list valist)
3178 {
3179 return vfprintf(stdout,format,valist);
3180 }
3181
3182 /*********************************************************************
3183 * vwprintf (MSVCRT.@)
3184 */
3185 int CDECL vwprintf(const wchar_t *format, va_list valist)
3186 {
3187 return vfwprintf(stdout,format,valist);
3188 }
3189
3190 /*********************************************************************
3191 * fprintf (MSVCRT.@)
3192 */
3193 int CDECL fprintf(FILE* file, const char *format, ...)
3194 {
3195 va_list valist;
3196 int res;
3197 va_start(valist, format);
3198 res = vfprintf(file, format, valist);
3199 va_end(valist);
3200 return res;
3201 }
3202
3203 /*********************************************************************
3204 * fwprintf (MSVCRT.@)
3205 */
3206 int CDECL fwprintf(FILE* file, const wchar_t *format, ...)
3207 {
3208 va_list valist;
3209 int res;
3210 va_start(valist, format);
3211 res = vfwprintf(file, format, valist);
3212 va_end(valist);
3213 return res;
3214 }
3215
3216 /*********************************************************************
3217 * printf (MSVCRT.@)
3218 */
3219 int CDECL printf(const char *format, ...)
3220 {
3221 va_list valist;
3222 int res;
3223 va_start(valist, format);
3224 res = vfprintf(stdout, format, valist);
3225 va_end(valist);
3226 return res;
3227 }
3228
3229 /*********************************************************************
3230 * ungetc (MSVCRT.@)
3231 */
3232 int CDECL ungetc(int c, FILE * file)
3233 {
3234 if (c == EOF)
3235 return EOF;
3236 if(file->_bufsiz == 0 && !(file->_flag & _IONBF)) {
3237 alloc_buffer(file);
3238 file->_ptr++;
3239 }
3240 if(file->_ptr>file->_base) {
3241 file->_ptr--;
3242 *file->_ptr=c;
3243 file->_cnt++;
3244 clearerr(file);
3245 return c;
3246 }
3247 return EOF;
3248 }
3249
3250 /*********************************************************************
3251 * ungetwc (MSVCRT.@)
3252 */
3253 wint_t CDECL ungetwc(wint_t wc, FILE * file)
3254 {
3255 wchar_t mwc = wc;
3256 char * pp = (char *)&mwc;
3257 int i;
3258 for(i=sizeof(wchar_t)-1;i>=0;i--) {
3259 if(pp[i] != ungetc(pp[i],file))
3260 return WEOF;
3261 }
3262 return mwc;