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