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